c - 将指针分配给结构 C 时出现段错误

标签 c tree segmentation-fault

我的代码在通过指针传递给函数的父节点下方的树结构中创建了两个新节点。将父节点指定为新节点的父节点工作正常,但程序在尝试将新节点指定为父节点的左右子节点时会抛出段错误

//Create new nodes
node* new1 = (node*)malloc(sizeof(node));
new1->parent = par;

node* new2 = (node*)malloc(sizeof(node));
new2->parent = par;

par->left = new1;
par->right = new2;

这是供引用的结构

typedef struct nd {   
  int data;                               
  struct nd* parent;
  struct nd* left;
  struct nd* right;
}node;

最佳答案

已解决:我没有考虑根尚未分配的情况。 (即传递的指针为 NULL)

关于c - 将指针分配给结构 C 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983541/

相关文章:

algorithm - 遍历任意树结构中的每条唯一路径(从根到叶)

c - 是什么导致该程序出现段错误?

C,代码 :Block, 另一个 sigsegv,列出

c - c中递归函数的输出

c - 从函数返回值的更好方法

tree - 如何在复杂游戏中的 MCTS 中执行 Roll-out

c++ - 二维字符指针数组 --> 段错误?

C 中用指针改变字符串的值

c - 将文件列表保存到数组或其他 C

c++ - 如何从基树类派生