Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 我的链表程序有什么问题?(分段故障)_C_Debugging_Linked List_Segmentation Fault - Fatal编程技术网

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

C 我的链表程序有什么问题?(分段故障),c,debugging,linked-list,segmentation-fault,C,Debugging,Linked List,Segmentation Fault,我正在尝试在我的链接列表的倒数第二位插入一个元素…请帮助我 我创建了一个函数来枚举值为1、2、3…的链表 然后我有一个在最后一秒插入的函数,然后我有一个显示列表的函数 #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,*t

我正在尝试在我的链接列表的倒数第二位插入一个元素…请帮助我 我创建了一个函数来枚举值为1、2、3…的链表 然后我有一个在最后一秒插入的函数,然后我有一个显示列表的函数

#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;
}
#包括
#包括
结构节点{
int数据;
结构节点*下一步;
}*head=NULL;
空白插入(整数x){
int i=1;
结构节点*temp,*temp2=head;
而(x>0){
x--;
temp=(结构节点*)malloc(sizeof(结构节点));
头部->数据=i++;
头部->下一步=温度;
压头=温度;
}
head->next=NULL;
头部=temp2;
}
void insertSecondLast(int x){
结构节点*prev,*insert,*temp=head;
insert=(结构节点*)malloc(sizeof(结构节点));
插入->数据=x;
while(head->next!=NULL){
prev=头部;
头部=头部->下一步;
}
上一步->下一步=插入;
插入->下一步=头部;
压头=温度;
}
无效显示(){
printf(“\n[”);
while(head->next!=NULL){
printf(“%d”,标题->数据);
头部=头部->下一步;
}
printf(“NULL]”;
}
内部主(空){
插入(4);
第二次插入(100);
显示();
返回0;
}

在insert函数中,您正在反引用NULL指针(head最初设置为NULL)。操作系统不允许取消引用空地址,因此在运行时会出现seg错误。

使用调试器。但是看看你的插入函数。在设置之前,您正在取消对头的引用。你第一次遇到
head->data=i++时,head持有的地址是什么?绝对阅读
显示
函数应该是
而(head){printf(“%d”,head->data);head=head->next;}
谢谢@David C.Rankin。。。我分配的内存现在运行。非常感谢。。。我在main函数中为head分配了内存。现在它运行了。谢谢