我想要一个动态的字符串数组,所以指向数组的指针 . 这是我的代码(我的程序在打印后崩溃):
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而崩溃,或者我不知道如何在场景中正确打印字符串 .
1 回答
当您取消引用指针(这是
((first->children)[i])
)时,您将获得指针所指向的内存的值 .在你的情况下
(*((first->children))[i])
是单个字符(即char
)而不是字符串 . 尝试将其打印为字符串将导致未定义的行为和可能的崩溃 .不要取消引用指针: