【发布时间】:2014-05-23 13:08:35
【问题描述】:
我在尝试创建一个简单的链表时不断遇到分段错误。问题似乎发生在 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");
}
【问题讨论】:
-
您的代码永远无法运行,因为
insert_at_beg()无法更改main()中first的值。您应该返回新的列表头。还有don't cast the return value ofmalloc()in C.
标签: c list linked-list segmentation-fault