2017-02-18 41 views
-1

我想要一個動態數組的字符串,所以指向數組的指針。 這是我的代碼(打印後,我的程序崩潰):配置一個二維數組,試圖打印字符串後崩潰

typedef struct person{ 
    char *name; 
    char **children; 
    struct person *nextPerson; 

}Person; 

int main(){ 
    int kidsNum = 1; 
    int i; 
    Person *first = (Person*)malloc(sizeof(Person)); 
    first->name = "George"; 
    first->children = malloc(kidsNum * sizeof(char*)); 
    for (i = 0; i < kidsNum; i++){ 
     //every string consists maximum of 80 characters 
     (first->children)[i] = malloc((80+1) * sizeof(char)); 
     scanf("%s",((first->children)[i])); 
     printf("%s",(*((first->children))[i])); 
    } 
} 

它的printf後崩潰,我不知道,如果它崩潰,因爲壞mallocing,或不知如何打印字符串在場景中正確。

+2

的參數應該是相同的打印字符數組/ –

+0

'的printf( 「%s」 時,(*((第一代>兒童)) [ - ]''printf(「%s \ n」,first-> children [i]);' – BLUEPIXY

+0

編譯啓用所有警告 –

回答

1

當您取消引用指針(這是((first->children)[i])所在的位置)時,將獲取指針指向的內存值。

在你的情況下,(*((first->children))[i])是一個單個字符(即一個char),而不是一個字符串。試圖將其作爲字符串打印將導致未定義的行爲和可能的崩潰。

不要取消引用指針:scanf函數與printf函數

printf("%s",first->children[i]); 
+0

哦,對我來說愚蠢,謝謝! – user3575645