#include<stdio.h>
#include<malloc.h>
typedef struct Node {
int data;
struct Node * next;
} Node;
void push(Node **headRef, int i){
//why does headRef == NULL in below if condition gives segmentation fault?
if(*headRef == NULL){
*headRef = malloc(sizeof(Node));
Node *head = *headRef;
head->data = i;
}
}
int main(int argc, char ** argv){
Node *head = NULL;
push(&head, 2);
printf("%d\n", head->data);
}
此代码是链接列表,我尝试将一些数据推送到列表中。 我的问题在于推送功能的评论。
答案 0 :(得分:0)
是的,segfault稍后访问head->data
(如果您使用headRef==NULL
)
答案 1 :(得分:0)
无需测试。如果* headRef恰好为NULL,则newnode-&gt; next将设置为NULL,否则设置为* headRef。
void push(Node **headRef, int i){
Node *new;
new = malloc(sizeof *new);
/* check for new==NULL omitted */
new->next = *headRef;
new->data = i;
*headRef = new;
}