下面是一個簡單的代碼,我試圖使用指針指向指向鏈表添加節點。指向指針的指針:引用成員中的錯誤
#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
我不能夠理解我要去的地方錯了究竟。
'*(根) - >數據= 5;' - >>'(*根) - >數據= 5;'BTW:你的代碼在某些代碼路徑上泄漏'* temp'內存。並且:除去演員,他們只能做傷害。 – wildplasser
它工作!謝謝@wildplasser。您能否簡單介紹兩種情況下的優先順序。 –
其他人已經做到了。 ' - >'和'。'具有最高的優先級(「綁定更緊密」); '*'是*較弱*。 '#include'malloc.h是一個非標準的頭文件。你想'stdlib.h' –
wildplasser