【发布时间】:2013-11-04 04:02:57
【问题描述】:
我的代码中有以下 sn-ps,我试图使用动态分配的 char * 数组来保存来自标准输入的字符串。
char **reference
reference = calloc(CHUNK, sizeof(char *));
我使用一个临时的静态数组先存储来自stdin的字符串,然后根据一定的条件将它复制到char *的数组中。我在运行时将内存分配给个人char *。
reference[no_of_ref]=malloc(strlen(temp_in) + 1);
reference[no_of_ref++]=temp_in;
// printf(" in temp : %s , Value : %s , Address of charp : %p\n",temp_in,reference[no_of_ref-1],reference[no_of_ref-1]);
memset(&temp_in,'\0',sizeof(temp_in));
pre_pip = -1;
}
/*If allocated buffer is at brim, extend it by CHUNK bytes*/
if(no_of_ref == CHUNK - 2)
realloc(reference,no_of_ref + CHUNK);
所以no_of_ref 保存了最终收到的字符串总数。例如 20。但是当我打印整个 reference 数组以查看每个字符串时,我得到了最后一个相同的字符串,打印了 20 次。
【问题讨论】:
标签: c arrays realloc char-pointer