我的链表程序有什么问题? (分段故障)

时间:2018-07-15 05:07:09

标签: c debugging linked-list segmentation-fault

我正在尝试在链接列表的倒数第二个位置插入元素...请帮帮我 我创建了一个函数来枚举值1,2,3 ... etc的链表 然后,我有一个要插入第二个函数,然后有一个要显示列表的函数。

#include <stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
}*head=NULL;
void insert(int x){
 int i = 1;
 struct node *temp,*temp2=head;
 while(x>0){
     x--;
     temp = (struct node*)malloc(sizeof(struct node));
     head->data=i++;
     head->next=temp;
     head=temp;
     }
     head->next=NULL;
head=temp2;
}

void insertSecondLast(int x){
struct node *prev,*insert,*temp=head;
insert = (struct node*)malloc(sizeof(struct node));
insert->data=x;
while(head->next!=NULL){
    prev = head;
    head=head->next;
    }
prev->next=insert;
insert->next=head;
head=temp;
}

void display(){
    printf("\n[");
    while(head->next!=NULL){
        printf("%d, ",head->data);
        head=head->next;
    }
    printf("NULL]");
}


int main(void) {

     insert(4);
     insertSecondLast(100);
     display();
     return 0;
}

1 个答案:

答案 0 :(得分:1)

在插入函数中,您正在取消引用NULL指针(头最初设置为NULL)。操作系统不允许您取消引用NULL地址,因此在运行时会遇到段错误。

相关问题