谁能帮我解决程序中的段错误
错误。
我最近开始使用链表,但我不知道我是否正确使用了 struct node
。如果使用错误,有人可以纠正我。谢谢!
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* root = NULL;
void append()
{
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter The Node Value: ");
scanf("%d",&temp->data);
temp->link=NULL;
if(root = NULL)
{
root = temp;
}
else
{
struct node* p;
p = root;
while(p->link != NULL)
{
p=p->link;
}
p = temp;
}
}
int main()
{
printf("Add A Node To The Structure:-\n");
while(1)
{
int ch;
printf("Enter 2 To Exit\n");
printf("Enter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 2: exit(0);
default:append();
}
}
return 0;
}
最佳答案
if(root = NULL)
将 null 分配给 root 而不是检查。
Null 被转换为 bool 值 false,因此执行 else block 。
使用 root
属性假设它是非 null 会导致段错误。
改为编写 if(root == NULL)
。
关于有人能告诉我段错误的原因吗 - 这个程序中的(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016552/