我正在研究this article.
的链接列表本教程的作者永远不会创建实际的节点,而只会创建node类型的指针变量,如下面的代码所示......
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。
这意味着需要创建另一个变量,然后需要声明变量的地址存储在指针变量中,然后才能解除引用...就像下面的代码... < / p>
int *a;
int b=5;
a=&b;
printf("%d",*a);
输出5。
那么作者如何避免创建节点呢?他只是创建指针变量,然后简单地解引它们....
答案 0 :(得分:4)
节点在堆中,这就是malloc
的用途。
要使用没有链接列表的代码来解释,它类似于:
int *a = NULL;
a = malloc(sizeof(int));
*a = 5;
printf("%d",*a);
答案 1 :(得分:0)
创建结构指针以便它们可以引用address。由于普通结构变量无法存储地址,因此这种语法是错误的。
struct node head;
struct node second;
struct node third;