我对这种 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/