【发布时间】:2020-10-22 23:18:24
【问题描述】:
我正在创建一个链接列表,但在阶梯下方的某个地方我没有正确分配地址以将它们链接在一起。
没有编译时错误,但是当我尝试打印 list.head->next 节点时,我的代码中的错误变得明显。打印结果为00000000的地址。
为什么没有分配list.head->next?
#include <stdlib.h>
#include <stdio.h>
struct Node
{
int data;
struct Node* next;
};
struct List
{
struct Node* head;
} list;
void insert_node(struct Node *new_node)
{
if (list.head == NULL)
{
list.head = new_node;
}
else
{
struct Node *temp = list.head->next;
while (temp != NULL)
{
temp = temp->next;
}
temp = new_node;
}
}
struct Node* create_node(int data)
{
static int node_number = 0;
struct Node * new_node= malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
printf("Node inside function %d - address: %p\n", node_number++, new_node);
return new_node;
}
int main()
{
struct Node *a = create_node(11);
struct Node *b = create_node(12);
insert_node(a);
insert_node(b);
printf("%p\n", list.head->next);
}
【问题讨论】:
-
您认为应该分配到代码的哪个位置?当您使用调试器对其进行跟踪时,为什么不会发生这种情况?
-
设置
temp = new_node;不会改变列表中任何节点的next成员。 -
调试器没有告诉我任何我可以亲自解释答案的信息。它编译并运行,这是我困惑的一部分。在
insert_node函数中,while 循环继续,直到找到new_node的可用插槽。如果list.head->next可用,则循环中断并将new_node 分配给该点。我做了两个插入实例,所以list.head由第一个插入分配,但现在list.head->next是下一个可用插槽未正确分配。
标签: c data-structures memory-management linked-list singly-linked-list