c - C 中的指针行为 : Initializing Linked List Head after Node

标签 c pointers

我对这种 C 行为有点困惑。如果我在节点之后初始化“头”指针,它似乎不会继续保留下一个元素。示例代码如下:

#include <stdio.h>
#include <stdlib.h>


typedef struct node {
    int value;
    struct node* next;
} node;

int main(void)
{
    node* head = NULL;
    node* current = malloc(sizeof(node));
    current->value = 1;

    if(head == NULL)
        head = current;

    current = current->next;

    current = malloc(sizeof(node));
    current->value = 2;

    printf("%d\n", current->value); // 2
    printf("%d\n", head->value); // 1
    printf("%d\n", head->next->value); //Segmentation fault: 11, Should be 2

    return 0;

}

据我了解:我使用 malloc() 获取当前内存,然后设置该值。然后设置水头等于电流。它们现在都指向同一个节点。

然后我使 current = current->next,malloc 内存并设置值。

为什么 head->next->value 不指向与 current->value 相同的位置?

最佳答案

这并不像你想象的那样:

current = current->next;

在此声明之前,您有以下内容:

             ---------------
current ---> |   1  |   ?  |
             ---------------

current 指向足以容纳 node 的内存区域,其中 value 的值为 1, 的值next 未知,因为 malloc 返回未初始化的内存。

在此语句之后,current 包含 current->next 包含的垃圾值。当你这样做时:

current = malloc(sizeof(node));

您将 current 的值更改为 malloc 返回的值,覆盖之前的值。

要实现您的预​​期,您需要执行以下操作:

current->next = malloc(sizeof(node));
current = current->next;

关于c - C 中的指针行为 : Initializing Linked List Head after Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46508435/

相关文章:

c++ - memcpy 和单个数据字的赋值语句有什么区别?

c - 三元搜索树的插入函数 - C

c - 当指针出现在变量(指针*)的末尾时,这意味着什么?

c++ - 使用已删除的 shared_ptr 中的原始指针的未定义行为?

c - 在 C 中重新解释内存的正确方法是什么?

c - 将结构成员传递给 c 中的函数

c - 如果条件变量向锁定的线程发出信号怎么办?

c - 在 C 中 move 当前堆栈帧

c - 访问从 void 指针转换的结构中的 char 指针

c - 写入另一个程序的标准输入/从 c 中另一个程序的标准输出读取