【发布时间】:2016-08-10 18:55:50
【问题描述】:
下面是一个简单的代码,我尝试使用指向指针的指针将节点添加到链表中。
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
void insert(struct node **root)
{
struct node * temp = (struct node *)malloc(sizeof(struct node));
if(*root == NULL)
{
*(root) = (struct node *) malloc (sizeof(struct node ));
*(root)->data = 5;
*(root)->next = temp;
}
else
printf("here");
}
int main()
{
struct node *root = NULL;
insert(&root);
return 0;
}
我的理解是,在 main() 中,一个块被分配给 root。在insert 中,该内存块的地址在参数中传递。然后它检查它们是否是分配给该地址的结构的任何内存块,如果它是 NULL 内存则分配给结构块。这应该被*root引用。但是当我执行上面的代码时,我得到了以下错误:
error: request for member 'data' in something not a structure or union
我无法理解我到底哪里出错了。
【问题讨论】:
-
*(root)->data = 5;-->>(*root)->data = 5;BTW:您的代码在某些代码路径上泄漏了*temp内存。并且:移除石膏,它们只会造成伤害。 -
成功了!谢谢@wildplasser。您能否简要解释一下这两种情况下的优先级有何不同。
-
其他人已经这样做了。
->和.具有最高优先级(“绑定更紧”);*较弱。而#include <malloc.h>malloc.h 是一个非标准的标头。你想要stdlib.h -
为
malloc使用正确的标头,即<stdlib.h>。 -
我已将您的问题编辑为引用“指向指针的指针”而不是“双指针”。 “双指针”可以是
double*类型。
标签: c pointers memory-leaks