2017-02-18 71 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