algorithm - 分段默认值
问题描述
创建节点:
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
..................................................... ..................................................... ......
Segmentation fault 是什么意思?如何摆脱它?我哪里错了?..................................................... ..................................................... …………
谢谢。
解决方案
当您尝试访问一些受限制的内存时,会发生分段错误。
出现错误是因为在您的情况下,链表是空的,当您第一次调用append函数时,它会转到您的if 语句,并且在您的 if 中head = temp;
,您正在使用临时数据更新您的头部。此外,当 if 条件结束时,您将返回 p 的值,return p->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;
推荐阅读
- sql - 可以在运行时调用过程中使用case语句吗
- accessibility - 如何处理屏幕阅读器的版本号?
- android - 录制屏幕时的Android方向问题
- ram - Nand闪存芯片;x8 和 x16 位的 I/O 宽度?
- python - Q 值太高,值变为 NaN,Q-Learning Tensorflow
- php - 如何在这个 PHP 脚本中添加序列号列?
- python - Python中的投注赔率组合
- visual-studio-code - 如何在 VSCode 终端中发送 SIGQUIT 或 SIGKILL
- javascript - React Native UseState 数组清除
- python - spacy lemmatizing 与 lemma_lookup 表不一致