c - 链接列表 - 什么会导致使用 malloc 分配的地址实际上从未被分配?
问题描述
我正在创建一个链接列表,并且在梯子下方的某个地方我没有正确分配地址以将它们链接在一起。
没有编译时错误,但是当我尝试打印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);
}
解决方案
在 else 语句中的函数 insert_node 内
else {
struct Node *temp = list.head->next;
while (temp != NULL)
{
temp = temp->next;
}
temp = new_node;
}
更改了未连接到列表的局部变量 temp。
你需要写
else {
struct Node *temp = list.head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
请注意,使函数依赖于全局变量是一个坏主意list
。在这种情况下,该函数无法处理其他列表。因此,对于每个列表,例如在程序中使用两个列表时,您需要编写一个单独的函数复制代码。
该函数至少可以按如下方式定义,如下所示。
void insert_node( struct List *list, struct Node *new_node )
{
struct Node **current = &list->head;
while ( *current != NULL ) current = &( *current )->next;
*current = new_node;
}
struct Node * create_node( int data )
{
static unsigned int node_number = 0;
struct Node *new_node = malloc( sizeof( struct Node ) );
if ( new_node != NULL )
{
new_node->data = data;
new_node->next = NULL;
printf("Node inside function %u - address: %p\n", node_number++, ( void * )new_node);
}
return new_node;
}
推荐阅读
- python-3.x - 基本 Flask SQLAlchemy 上下文问题
- c - 以字符串文字作为参数的 strtok
- regex - MongoDB $regex 查询号码失败
- chart.js - 如何去除彩色标签方块
- go - graphql-go 将字段类型定义为对象
- google-sheets - 比较两行中的每个单元格,但有一个例外
- dynamics-crm - MS Dynamics CRM 365 - 从 Excel 文件导入数据
- canon-sdk - 读取 CR2 文件时 Canon EDSDK.EdsGetImage 错误 EDS_ERR_NOT_SUPPORTED
- pandas - 过滤多个 between_time 和 ID 条件
- mysql - 我从不选择的 MySQL 主键