gpt4 book ai didi

c - 创建链表时不需要创建实际节点吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:41 25 4
gpt4 key购买 nike

我正在研究来自 this article. 的链表

本教程的作者从不创建实际的节点,而只创建节点类型的指针变量,如您在以下代码中所见...

struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

然后他在堆中为它们分配空间...

head = (struct node*)malloc(sizeof(struct node)); 
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));

他为什么不创建实际节点?代码应该看起来像这样......

struct node head;
struct node second;
struct node third;

如果我的知识是正确的(如果我错了请纠正我)。简单地声明指针变量不会创建实际变量(在链表的情况下为节点),因此不能像文章中使用代码的教程作者那样取消引用

head->data = 1;

我的意思是,如果这行得通,那为什么行不通呢?

int *a;
a=5;
printf("%d",*a);

显然,上面的代码并没有输出5。

这意味着需要创建另一个变量,然后需要声明变量的地址存储在指针变量中,然后才能对其进行解引用...就像下面的代码...

int *a;
int b=5;
a=&b;
printf("%d",*a);

这输出 5。

那么作者是如何逃避不创建节点的呢?他只是简单地创建指针变量,然后简单地取消对它们的引用....

最佳答案

节点在堆中,这就是 malloc 的作用。

用不用链表的代码来解释,类似于:

int *a = NULL;
a = malloc(sizeof(int));
*a = 5;
printf("%d",*a);

关于c - 创建链表时不需要创建实际节点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25966051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com