任务:
我在 filtered_records
中有一个记录数组,过滤记录的数量在
num_filtered_records
。我想在 binfo->filtered_records
中复制此信息
和 binfo->num_filtered_records
因为 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*));
问题:
当我打印 binfo->filtered_records
时,我看到了所有记录,但有些记录有
被不正确的值所取代。我不确定我错过了什么。
最佳答案
您所做的并不会复制实际数据,它只是复制指针。代替那个 memcpy
,做一个 for:
for (i = 0; i < num_filtered_records; i++)
binfo->filtered_records[i] = strdup(filtered_records[i]);
如果您没有 strdup
,请使用 malloc(strlen(filtered_records[i]) + 1)
,然后使用 strcpy
。
关于复制 char 指针数组的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9531184/