[英]C - Getting Segmentation fault(core dumped)
我刚开始学习树并想实现它。此代码编译但运行后我得到分段错误。我有
有2个功能
1."new" 这将创建一个新节点以添加到树中
2."insert" 这会将数据插入树,这是一个递归 function
我只想检查数据是否正在存储,所以我尝试在根节点中打印值,但随后出现分段错误
我检查了所有似乎正确但不知道出了什么问题的东西
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* new(int data)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node*));
newnode->data=data;
newnode->left=newnode->right=NULL;
return newnode;
}
struct node* insert(struct node* root,int data)
{
if(root==NULL)
{
new(data);
}
else if (data<=root->data)
{
root->left =insert(root->left,data);
}
else
{
root->right=insert(root->right,data);
}
return root;
}
void main()
{
struct node* root = NULL;
root = insert(root,15);
root = insert(root,20);
printf("%d",root->data);
}
我希望 output 为 15,但会出现分段错误。
您不会将数据存储在任何地方。 更改new(data);
到root = new(data);
在insert
function 中。
另一个错误是struct node* newnode = (struct node*)malloc(sizeof(struct node*))
应该是struct node* newnode = malloc(sizeof(*newnode))
。 这既修复了错误,又因其他原因而变得更好。
此外, void main()
应该是int main()
。
您必须更改 malloc 表达式。 您应该 malloc 结构节点而不是结构节点*。 此外,您应该将 void main 更改为 int main
首先,您确定要更改struct node* newnode = (struct node*)malloc(sizeof(struct node*));
to struct node* newnode = (struct node*)malloc(sizeof(struct node));
,删除 sizeof 中的星号,否则无论结构的大小如何,您都会得到 8 个字节的大小;)
然后你得到一个stackoverflow错误,但我让你搜索那个;p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.