我真的不明白为什么我会在这里出现段错误。这是有史以来最简单的代码。
基本上,我有这个简单的节点结构
struct node {
int value;
struct node *left_child;
struct node *right_child;
};
当我像这样测试这个节点结构时:
struct node *m_node;
m_node->value = 10;
printf("%d\n", m_node->value);
这里一切正常。
现在,有了这个简单的树结构,事情就开始崩溃了。
struct tree {
int size;
struct node *head;
};
我尝试像这样测试它:
struct tree *m_tree;
m_tree->head = m_node;
printf("%d\n", m_tree->head->value);
我遇到了段错误。有什么想法吗?
最佳答案
您已经创建了一个悬空指针。 malloc()
一个空格,或者将其分配给已创建的结构的地址:
struct tree *m_tree=malloc(sizeof(struct tree)); // Either this
struct tree *m_tree=&some_node; // Or this
关于c - 创建树时出现段错误(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509480/