繁体   English   中英

等式双指向NULL的指针在C中给出分段错误

[英]equation double pointer to NULL gives segmentation fault in C

#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);
}

这段代码是链表,我尝试将一些数据推入链表。 我的问题是在推功能的评论。

是的,segfault稍后会在head->data访问中(如果您使用headRef==NULL

无需测试。 如果* headRef恰好为NULL,则newnode-> 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;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM