为什么我不能在 C 中初始化和声明指向 NULL 的指针?
Why can't I initialize and declare pointer to pointer to NULL in C?
我写了一个C程序。函数内部的部分代码如下所示:
struct node* functionName(struct node *currentFirstPointer){
struct node **head = NULL;
*head = currentFirstPointer;
return *head;
}
这里node
是一个结构体。但是当我 运行 程序时,这一行给了我一个 segmentation fault
。但是,如果我像下面这样在同一个函数内的单独语句中声明并初始化指向指针的指针,那么它就可以正常工作。
struct node* functionName(struct node *currentFirstPointer){
struct node **head;
*head = NULL;
*head = currentFirstPointer;
return *head;
}
第一个块不工作而第二个块工作正常的原因可能是什么?
您有两个取消引用指针的示例。
struct node **head = NULL;
*head = currentFirstPointer;
和
struct node **head;
*head = NULL;
*head = currentFirstPointer;
两者都是未定义行为的原因。首先,您取消引用 NULL 指针。在第二个中,您取消引用了一个未初始化的指针。
第二个块似乎可以工作,但这是未定义行为的问题。
您需要先为 head
分配内存,然后才能取消引用指针。
struct node **head = malloc(sizeof(*head)*SOME_COUNT);
*head = currentFirstPointer;
我写了一个C程序。函数内部的部分代码如下所示:
struct node* functionName(struct node *currentFirstPointer){
struct node **head = NULL;
*head = currentFirstPointer;
return *head;
}
这里node
是一个结构体。但是当我 运行 程序时,这一行给了我一个 segmentation fault
。但是,如果我像下面这样在同一个函数内的单独语句中声明并初始化指向指针的指针,那么它就可以正常工作。
struct node* functionName(struct node *currentFirstPointer){
struct node **head;
*head = NULL;
*head = currentFirstPointer;
return *head;
}
第一个块不工作而第二个块工作正常的原因可能是什么?
您有两个取消引用指针的示例。
struct node **head = NULL;
*head = currentFirstPointer;
和
struct node **head;
*head = NULL;
*head = currentFirstPointer;
两者都是未定义行为的原因。首先,您取消引用 NULL 指针。在第二个中,您取消引用了一个未初始化的指针。
第二个块似乎可以工作,但这是未定义行为的问题。
您需要先为 head
分配内存,然后才能取消引用指针。
struct node **head = malloc(sizeof(*head)*SOME_COUNT);
*head = currentFirstPointer;