在尝试创建一个简单的链表时,我一直遇到段错误。这个问题似乎出现在 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");
}
最佳答案
让它返回列表的新头部:
void insert_at_beg(struct node *first, double x)
{
struct node *temp = getnode();
temp->value = x;
temp->next = first;
return temp;
}
也比较简单。 :)
然后在 main()
中,执行:
struct node *first = insert_at_beg(NULL, 10.2);
first = insert_at_beg(first, 17.8);
关于c - 分段故障链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830117/