c - 指向结构的指针中的结构指针数组

标签 c memory-management tree

下面的代码尝试初始化一个节点,并在此过程中动态初始化一个指向子节点的指针数组。但是,当我尝试访问子项时,出现了 Segmentation fault: 11。我意识到我不应该得到任何有意义的值(即它只会成为内存中的垃圾)但我不知道为什么我会遇到段错误。

#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>

#define INIT_SIZE 10

typedef struct node_t node_t;

struct node_t {
  char *word;
  node_t **children;
  int arr_len;
};

void set_array_vals(node_t *root);

int main(int argc, char const *argv[]) {
    char *word = "hello";

    node_t *root = malloc(sizeof(node_t));
    assert(root);

    root->children = malloc(sizeof(node_t *) * INIT_SIZE);
    assert(root->children);
    root->arr_len = INIT_SIZE;

    root->word = malloc((sizeof(char)) * (strlen(word) + 1));
    assert(root->word);
    strcpy(root->word, word);

    set_array_vals(root);
    printf("Arr len: %d\n", root->arr_len);

    return 0;
}

void set_array_vals(node_t *root) {
    int i;
    for (i=1; i<root->arr_len; i++) {
        node_t *this_node = root->children[i];
        printf("%d: %d\n", i, this_node->arr_len);
    }
}

最佳答案

set_array_vals 中,您从“数组”root->children 中获取指针,但该数组未初始化,指针将不确定 并且看似随机。取消引用这些指针会导致 undefined behavior .

此外,您似乎忘记了数组索引从 开始。一旦你使 root->children 数组中的所有指针都有效,你必须记住也要初始化它们指向的结构,否则 this_node->arr_len 的值> 将不确定。

关于c - 指向结构的指针中的结构指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407088/

相关文章:

c - 在这些声明下,以下表达式是什么类型,它们是否正确?

c - 通过 malloc 生成的数组与不是通过 malloc 生成的数组有何不同

c++ - 在 C++ 中使用 std::allocator::allocate(0) 分配零个对象

c++ - 取消引用被转换为双指针的指针

tree - 在序言中声明树的好方法?

c++ - 将树展平为链表c++,没有指针

c - 在这种情况下,什么是有效的,将指针的地址分配给指针或使用 strcpy?

c - 错误: ‘struct tty_driver’ has no member named ‘ioctl’

c++ - 从程序执行批处理文件

c++ - 树节点森林 C++?