c - 链表 C 中的分段错误
问题描述
下面是我的程序,我尝试了几种方法,但我无法得出结论,因此卡住了,有人可以帮忙吗?
有什么问题和任何替代方法?
struct Node
{
int data;
struct Node *prev,*next;
};
插入元素
void push(struct Node *start,struct Node *end,int x,int loc)
{
struct Node *new=(struct Node*)malloc(sizeof(struct Node));
new->data=x;
if(start==NULL)
{
new->next=NULL;
new->prev=NULL;
start=new;
end=new;
}
else
{
if(loc==1)
{
new->prev=NULL;
new->next=start;
start->prev=new;
start=new;
}
else
{
struct Node *ptr=start;
for(int i=0;i<loc-1;i++)
{
ptr=ptr->next;
}
if(ptr->next==NULL)
{
new->next=NULL;
new->prev=ptr;
ptr->next=new;
end=new;
}
else
{
new->next=ptr->next;
new->prev=ptr;
ptr->next->prev=new;
ptr->next=new;
}
}
}
}
从头开始显示
void display_start(struct Node *temp)
{
struct Node *ptr=NULL;
for(ptr=temp;ptr->next!=NULL;ptr=ptr->next)
{
printf("%d\t",ptr->data);
}
printf("%d",ptr->data);
}
从末端显示
void display_end(struct Node *temp2)
{
struct Node *ptr=NULL;
for(ptr=temp2;ptr->prev!=NULL;ptr=ptr->prev)
{
printf("%d\t",ptr->data);
}
printf("%d",ptr->data);
}
主功能
int main(void) {
// your code goes here
struct Node* head=NULL;
struct Node* tail=NULL;
push(head,tail,1,1);
push(head,tail,2,2);
push(head,tail,3,2);
push(head,tail,4,3);
push(head,tail,5,5);
push(head,tail,6,4);
printf("From Start: ");
display_start(head);
printf("From End: ");
display_end(tail);
return 0;
}
一个编译器显示垃圾值,另一个显示分段错误
据我所知,显示列表时出现错误。
解决方案
display_start()
不打印列表的 一个可能原因是,您传递了在 C 中被视为按值调用的head
to函数。因此,您在函数中进行的任何修改都不会在函数中受到影响,并且列表仍然为空。push()
head
push()
main()
不只是传递head
给push()
函数,而是传递 的地址head
,同样适用于tail
也。
例如
push(&head,&tail,1,1);
并做相应的push()
功能变化。
void push(struct Node **start,struct Node **end,int x,int loc) {
/* Do changes here */
}
-Wall
还要用类似标志编译你的程序,gcc -Wall test.c
不要忽略警告,解决它们。通过编译更好地将所有警告视为错误,-Wstrict-prototypes -Werror
以便减少错误的机会。例如
gcc -Wall -Wstrict-prototypes -Werror test.c
最后学习如何调试小代码https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
推荐阅读
- node.js - 使用 mongoosastic 在全文搜索中进行模糊搜索
- json - 单引号字符串中的 Powershell 变量扩展
- java - NullPointerException 没有行号的错误。如何在 Android Studio 中获取导致此错误的行号?
- microsoft-cognitive - 运行认知服务读取文本容器预览时出错
- visual-studio - Deploy/debug app from VS 2019 to windows 10 mobile phone via USB
- python - 带有 Sphinx Python 文档生成器错误的 Graphviz 图
- python - Flask Route REcorator 中有两个或多个变量?
- html - 如何将页脚与底部对齐
- c++ - 移动简单纹理时的 SDL2 常规抖动 - 即使在没有 vsync 的情况下以高 fps
- android-studio - 为什么我在 Fragment 中的 TabLayout 只能在第一次使用?