简体   繁体   English

为什么我不能在C语言中初始化和声明指向NULL的指针?

[英]Why can't I initialize and declare pointer to pointer to NULL in C?

I wrote a C program. 我写了一个C程序。 Some part of the code which is inside a function looks like this: 函数内部的部分代码如下所示:

struct node* functionName(struct node *currentFirstPointer){
    struct node **head = NULL;
    *head = currentFirstPointer;
    return *head;
}

Here node is a structure. 这里的node是一个结构。 But this line gives me a segmentation fault when I run the program. 但是,当我运行程序时,此行给我一个segmentation fault But if I declare and initialize the pointer to pointer in separate statements inside the same function like below then it works fine. 但是,如果我在如下所示的同一函数内的单独语句中声明并初始化指向指针的指针,则它可以正常工作。

struct node* functionName(struct node *currentFirstPointer){
    struct node **head;
    *head = NULL;
    *head = currentFirstPointer;
    return *head;
}

What could be the reason that the 1st block doesn't work and the 2nd block works fine? 第一个块不起作用而第二个块正常工作的原因可能是什么?

You have two examples of dereferencing a pointer. 您有两个取消引用指针的示例。

struct node **head = NULL;
*head = currentFirstPointer;

and

struct node **head;
*head = NULL;
*head = currentFirstPointer;

Both are cause for undefined behavior. 两者都是导致未定义行为的原因。 In the first, you are dereferencing a NULL pointer. 首先,您要取消引用NULL指针。 In the second, you are dereferencing an uninitialized pointer. 在第二个中,您将取消引用未初始化的指针。

The second block may appear to work but that's the problem with undefined behavior. 第二个块可能似乎起作用,但这就是未定义行为的问题。

You need to allocate memory for head first before you can dereference the pointer. 您需要先为head分配内存,然后才能取消引用指针。

struct node **head = malloc(sizeof(*head)*SOME_COUNT);
*head = currentFirstPointer;

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

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