Algorithm 分段默认值
创建节点:Algorithm 分段默认值,algorithm,data-structures,linked-list,segmentation-fault,singly-linked-list,Algorithm,Data Structures,Linked List,Segmentation Fault,Singly Linked List,创建节点: struct Node { int data; struct Node *link; }; struct Node *head = NULL; 附加函数 int append() { struct Node *temp; struct Node *p; temp = (struct Node *)malloc(sizeof(struct Node)); printf("Enter the data");
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
附加函数
int append()
{
struct Node *temp;
struct Node *p;
temp = (struct Node *)malloc(sizeof(struct Node));
printf("Enter the data");
scanf("%d", &temp->data);
if (head == NULL)
{ temp->link = NULL;
head = temp;
}
else
{
p = head;
while (p != NULL)
{
p = p->link;
}
p->link=NULL;
}
return p->data;
}
主要功能
void main()
{
int append();
int insert();
int insert_begin();
int display();
int delete ();
int del_between();
int k = 1, ch ,d;
while (k)
{
printf("\nEnter choice\n");
printf("1.Append\n");
printf("2.In between\n");
printf("3.At the beginning\n");
printf("4.Display\n");
printf("5.Delete\n");
printf("6.Delete from between\n");
printf("7.Quit\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
d = append();
printf("pushed %d",d);
break;
case 2:
insert();
break;
case 3:
insert_begin();
break;
case 4:
display();
break;
case 5:
delete ();
break;
case 6:
del_between();
break;
case 7:
k = 0;
break;
default:
printf("wrong choice");
}
}
}
我一直试图在链表的末尾添加一个节点,但一旦输入要添加的数据,就会出现默认错误
输出屏幕
Enter choice
1.Append
2.In between
3.At the beginning
4.Display
5.Delete
6.Delete from between
7.Quit
1
Enter the data23
Segmentation fault
徖
分段错误的含义是什么?如何消除它?我哪里做错了?
徖
谢谢。当您试图访问某些受限制的内存时,会出现分段错误 出现此错误的原因是,在您的情况下,链接列表为空,并且第一次调用append函数时,会转到您的if语句,并且在您的if
head=temp代码>所以你正在用临时数据更新你的头部。此外,当if条件结束时,您将返回preturnp->data的值代码>但这不起作用
因为p只被初始化,但没有数据值,因此访问未分配给SIGSEGV的内容
您可以通过编辑以下内容来解决此错误:
if (head == NULL)
{ temp->link = NULL;
head = temp;
return head->data;
}
else
{
p = head;
while (p != NULL)
{
p = p->link;
}
p->link=temp;
p=temp;
temp->link=NULL;
}
return p->data;
描述问题时,必须准确报告错误消息。没有什么比得上“分段默认值”。请参阅“相关”下的超链接。还有。我是数据结构的初学者,你能帮我修改一下代码吗?是的,只需要包含returnhead->data代码>在append函数的if语句中,代码将正常工作。@TanyaGupta我还更新了ans。在需要时进行代码编辑,最后,您的append函数现在将返回刚刚附加到链接列表末尾的数据的int值。您如何对您的建议是否会产生有效的代码形成意见<代码>您可以解决错误[如下]
否。包括返回头->数据代码>又错了。@greybeard我承认代码无效,但它解决了分段错误,我只是提供了一个解决方案,以便用户能够使用它。