C - Pointer problems - how to fill array with value pointer is pointing to?
I have a function
void add_car(char *car) {
park.buffer[park.size] = car;
park.size ++;
}
car is a string like "XYZ". Atm, It 开发者_Go百科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
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
.
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.
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.
精彩评论