首页 > 解决方案 > 将指针分配给结构 C 时出现分段错误

问题描述

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

//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;

标签: ctreesegmentation-fault

解决方案


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


推荐阅读