简体   繁体   English

C-指针问题-如何用指针指向的值填充数组?

[英]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". car是类似“ XYZ”的字符串。 Atm, It seems to assign the carpark buffer array element to an address. Atm,似乎将停车场缓冲区数组元素分配给一个地址。 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. 因此,如果我用10辆汽车填充阵列,我会拿回10辆汽车,但由于汽车的地址已被覆盖,所以每辆都是最新的。 How do I fill my carpark.buffer with the actual value of a car. 如何用汽车的实际值填充carpark.buffer。

Total mindblank atm 完全空白的atm

Assuming park.buffer is an array of char* , you may want to use 假设park.bufferchar*的数组,则可能要使用

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;-)]). 请注意,这不可避免地会复制一个park 拥有副本 (必不可少,如果您不希望对car进行进一步更改以影响park.buffer !),这意味着完成后,您将不得不从那里free它,因为strdup隐式地执行malloc [当然也包括strcpy ;-)])。

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 . 顺便说一句,您需要在文件顶部#include <string.h> (如果尚未这样做)才能使用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. 但我认为park.buffer是一个指针数组。

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. 另外,您应该非常注意如何使用add_car函数。 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. 您正确= =设置字符串的地址,而不是复制整个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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