2013-11-04 25 views
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次。

回答

3

這裏代碼的引入問題:

reference[no_of_ref]=malloc(strlen(temp_in) + 1); 
reference[no_of_ref++]=temp_in; 

這是因爲在C指針的分配影響指針,只有指針,它不會做其內容的任何信息。您應該使用之類的東西memcpystrcpy

reference[no_of_ref]=malloc(strlen(temp_in) + 1); 
strcpy(reference[no_of_ref], temp_in); 
no_of_ref+=1; 
+0

Bahh ......這事我知道,仍然忘不了,每次我用的char *複製工作。感謝您再次提醒..! –

+0

@DiwakarSharma很高興幫助:) – starrify