错误:分段错误(代码转储)

时间:2016-09-15 06:58:57

标签: c data-structures

我是数据结构的新手,并从链接列表开始,我试图在链表的末尾添加元素,但得到错误分段错误。 我用C语言实现它。

我不明白这个错误意味着什么

CODE:

struct node 
{
int data;
struct node *next;
};
struct node *head;
void fnInsert(int x){
    if(head==NULL){
    printf("head is null");
    node* temp=(node*)malloc(sizeof(struct node));
    temp->data=x;
    temp->next=head;
    head=temp;
    }
    else{
        node* temp=head;
        struct node* previousNode;
        do{
            temp=temp->next;
            previousNode=temp;
        }while(temp!=NULL);
        node* temp1=(node*)malloc(sizeof(struct node));
            temp1->data=x;
            previousNode->next=temp1;
            temp1->next=NULL;
    }
};
void fnPrint(){
   struct node* temp=head;
   printf("list is:\n");
   while(temp!=NULL){
       printf("%d",temp->data);
       temp=temp->next;
       printf("\n");
   }
}
int main(){
    head=NULL;
    printf("how many numbers\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        printf("Enter the number\n");
        scanf("%d",&x);
        fnInsert(x);
        fnPrint();
    }
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:5)

错误在以下几行:

temp=temp->next;
previousNode=temp;

它应该相反,即

previousNode=temp;
temp=temp->next;

在您的情况下previousNode最终变为NULL并且您正在尝试访问previousNode->next,即取消引用NULL指针。所以这是一个分段错误。

此外,您在许多地方都使用过node*。您应该使用struct node*替换所有这些内容,或者typedef