1
我從我的代碼中得到了下面的代碼片段,我嘗試使用動態分配的char *
數組來保存來自stdin的字符串。C:字符指針數組未按預期動態工作
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次。
Bahh ......這事我知道,仍然忘不了,每次我用的char *複製工作。感謝您再次提醒..! –
@DiwakarSharma很高興幫助:) – starrify