c - Mallocing 二维数组,尝试打印字符串后崩溃

标签 c pointers multidimensional-array malloc

我想要一个动态字符串数组,因此指针指向数组的指针。 这是我的代码(我的程序在打印后崩溃):

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 之后崩溃,我不知道它是否因为错误的内存分配而崩溃,或者我不知道如何在场景中正确打印字符串。

最佳答案

当您取消引用指针时(这就是((first->children)[i])),您将获得指针所指向的内存的值。

在您的情况下 (*((first->children))[i]) 是一个单个字符(即 char)而不是字符串。尝试将其打印为字符串将导致未定义的行为并可能导致崩溃。

不要取消引用指针:

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

关于c - Mallocing 二维数组,尝试打印字符串后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320482/

相关文章:

c - 分配动态二维字符数组

c - 从线程中断 main 中的 while 循环。 (C语言编程)

c - 使用通用字段初始化结构的通用 API

c - 返回函数中声明的数组返回C中局部变量的地址?

php - 使用 array_diff 比较关联数组和数值数组

c++ - 无法在我的 C++ 类中初始化 2d Vector

c++ - _stprintf_s 将 "10"视为 "1"

c - 使用不同程序中的函数

c - 使用指针作为参数传递

c++ - 从类中删除指向 this 的指针?