简体   繁体   中英

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 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 .

要在C语言中复制“字符串”,您需要使用strcpy并且您不想将其复制到park.buffer的末尾,您可能希望将其复制到第0个位置。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM