tags:

views:

77

answers:

3

I have a function

void add_car(char *car) {
    park.buffer[park.size] = car;
    park.size ++;
}

car is a string like "XYZ". Atm, It seems to assign the carpark buffer array element to an address. Thus if I fill the array with 10 cars, I get back 10 cars, but each of them is the latest one, since the address of car was overwritten. How do I fill my carpark.buffer with the actual value of a car.

Total mindblank atm

+2  A: 

To copy a "string" in C you need to use strcpy and you don't want to copy it to the end of park.buffer, you probably want to copy it to the 0th position.

Mark E
+1  A: 

It's hard to tell exactly what you're doing without more context. But I assume park.buffer is an array of pointers.

since the address of car was overwritten

The address of car is not overwritten.

Also you should be very careful about how you are using the add_car function. If you keep calling it you will probably overwrite memory that is not yours. Also you'll want to be careful that what you pass into this function doesn't get freed since you are capturing its address.

You are correct about = setting the address of the string though and not copying the entire string over.

Brian R. Bondy
+3  A: 

Assuming park.buffer is an array of char*, you may want to use

park.buffer[park.size] = strdup(car);

Note that, inevitably, this makes a copy (indispensable, if you don't want further changes to car to affect park.buffer!) owned by park (meaning that, when done, you'll have to free it from there, because strdup implicitly does a malloc [and a strcpy too of course;-)]).

BTW, you'll need to #include <string.h> at the top of your file (if you're not already doing so) in order to use strdup.

Alex Martelli
Yep, char* is an array of char*, thanks.
Dominic Bou-Samra
@Dominic, then `strdup` sounds right (but do remember to `free` them in the end!-).
Alex Martelli
`strdup()` is not a standard function; it's POSIX (nothing wrong with that). Just thought I'd mention it.
pmg