[英]C: array of char pointers not working as expected dynamically
我在我的代碼中有以下代碼片段,我試圖使用動態分配的char *
數組來保存來自stdin的字符串。
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
保存最終收到的字符串總數。 例如,但是當我打印整個reference
數組以查看每個字符串時,我得到的是最后一個字符串,打印20次。
您的代碼在這里介紹了問題:
reference[no_of_ref]=malloc(strlen(temp_in) + 1);
reference[no_of_ref++]=temp_in;
那是因為C中的指針賦值會影響指針和指針,這些指針不會對其內容做任何事情。 你應該使用memcpy
或strcpy
類的東西:
reference[no_of_ref]=malloc(strlen(temp_in) + 1);
strcpy(reference[no_of_ref], temp_in);
no_of_ref+=1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.