[英]Segmentation fault linked lists
I keep getting a segmentaion fault when trying to create a simple linked list.The problem seems to occur inside the print_list function.I've been trying to fix this for about an hour but it's still not working.I'd really appreciate your help.This is the code: 我在尝试创建一个简单的链表时遇到了一个段错误。这个问题似乎发生在print_list函数中。我一直试图解决这个问题大约一个小时但它仍然没有工作。我真的很感激你的帮助这是代码:
#include<stdio.h>
#include<stdlib.h>
struct node{
double value;
struct node *next;
};
struct node* getnode()
{
struct node* create;
create=(struct node*)malloc(sizeof(struct node));
create->next=NULL;
return create;
}
void insert_at_beg(struct node*first,double x)
{
struct node*temp=getnode();
if(!first)
{
temp->value=x;
first=temp;
}
else
{
temp->value=x;
temp->next=first;
first=temp;
}
}
void print_list(struct node*first)
{
struct node*temp;
temp=first;
if(temp==NULL)
{ printf("The list is empty!\n");
return;
}
while(temp!=NULL)
if(temp->next ==NULL) // this is where i get the segmentation fault
{ printf("%lf ",temp->value);
break;
}
else
{
printf("%lf ",temp->value);
temp=temp->next;
}
printf("\n");
}
int main()
{
struct node *first;
insert_at_beg(first,10.2);
insert_at_beg(first,17.8);
print_list(first);
system("PAUSE");
}
Make it return the new head of the list: 让它返回列表的新头:
void insert_at_beg(struct node *first, double x)
{
struct node *temp = getnode();
temp->value = x;
temp->next = first;
return temp;
}
A bit simpler, too. 也有点简单。 :) :)
Then in main()
, do: 然后在main()
,执行:
struct node *first = insert_at_beg(NULL, 10.2);
first = insert_at_beg(first, 17.8);
You have an invalid address from the temp->next call. 你有一个来自temp-> next call的无效地址。 C does not default initialize variables you need to to set the first value to NULL C不会默认初始化您需要将第一个值设置为NULL的变量
struct node* first = NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.