繁体   English   中英

C中的指针行为:在节点之后初始化链接列表头

[英]Pointer Behaviour in C: Initializing Linked List Head after Node

我对此C行为感到有些困惑。 如果我在节点之后初始化“ head”指针,则它似乎不会继续保留下一个元素。 下面的示例代码:

#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,分配内存并设置该值。

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

要创建两个链接的节点,您需要将第next节点保存在第二个节点next

更改

current = current->next;

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

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

这将创建一个新节点(重用您已经分配给head的当前指针)并将其附加到head

在实践中,虽然您可能不想像这样将其附加到head因为它不能像2以后那样工作。您想要在列表的末尾,列表的开头创建一个新条目,或将其插入在列表的中间。

这不会按照您认为的那样做:

current = current->next;

在此声明之前,您具有以下条件:

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

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

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

current = malloc(sizeof(node));

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

要执行您想要的操作,您需要这样做:

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

暂无
暂无

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

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