任务:
我在filtered_records
中有一个记录数组,其中num_filtered_records
我想将此信息复制到binfo->filtered_records
因为binfo->num_filtered_records
以后在我的代码中是免费的。
定义:
char** filtered_records;
size_t num_filtered_records;
代码段:
binfo->filtered_records = malloc(num_filtered_records*sizeof(char*));
memcpy(binfo->filtered_records,
filtered_records,
num_filtered_records * sizeof(char*));
问题:
当我打印
filtered_records
时,我看到所有记录,但有些记录被错误的值替换我不知道我错过了什么。
最佳答案
你所做的并不是复制实际的数据,而是复制指针而不是memcpy
,执行以下操作:
for (i = 0; i < num_filtered_records; i++)
binfo->filtered_records[i] = strdup(filtered_records[i]);
如果没有
strdup
,请使用malloc(strlen(filtered_records[i]) + 1)
然后strcpy
。关于c - 复制char指针数组的正确方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9531184/