下面的代码尝试初始化一个节点,并在此过程中动态初始化一个指向子节点的指针数组。但是,当我尝试访问子项时,出现了 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/