下面的代码给出了gcc编译器的分段错误。早些时候它工作正常,但更新我的编译器后不工作。不知道发生了什么,它在一些在线编译器中工作。
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
//push function to add node at the beginning
void push(struct node** head,int data){
//creating new node
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
//pointing to head if not null
if((*head) != NULL)
newNode->next = (*head);
//making new node as head
(*head) = newNode;
}
//fuction to display linked list
void display(struct node* head){
while(head!=NULL){
printf("%d ",head->data);
head=head->next;
}
printf("n");
}
int main(){
struct node* head;
push(&head,20);
push(&head,10);
push(&head,5);
display(head);
return 0;
}
在push函数中,你已经检查了head是否为NULL,但是当你从main传递head时,你还没有将它初始化为NULL。
struct node* head;
应修改为
struct node* head = NULL;