c - 创建树时出现段错误(C)

标签 c

我真的不明白为什么我会在这里出现段错误。这是有史以来最简单的代码。

基本上,我有这个简单的节点结构

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/

相关文章:

c# - 你能理解这段 C 指针代码吗?

c - 在c中打印字符串的未知错误

c - C 中使用 fork() 和命令行参数的并行进程

c - 连接字符串和数字的最佳方式是什么 - 使用 C 的性能?

c - 段错误 :I can't understand why

c - 多线程服务器设计

ANSI C 中表达式的条件编译和编译时评估

c - 在链表中插入

C编程: How to use gdb with Makefile and command line arguments?

c - Makefile 不会在 header 修改时重建对象