我試過和提煉下面的代碼儘可能:C結構的typedef和聲明造成指針錯誤
#include <stdlib.h>
typedef struct item{
struct item *next;
}item;
void addItem(item *list)
{
item *newItem = list;
while(newItem->next != NULL){
newItem = newItem->next;
}
newItem->next = malloc(sizeof(item));
newItem->next->next = NULL;
}
int main()
{
item *groceryList = NULL;
groceryList = malloc(sizeof(item));
if(groceryList == NULL)
return 1;
groceryList->next = NULL;
addItem(groceryList);
return 0;
}
編譯沒有問題。但改變結構聲明(或變化的任意組合):
structpointertest.c:11:11: warning: assignment from incompatible pointer type structpointertest.c:15:15: error: request for member 'next' in something not a structure or union
我不明白,在結構聲明是什麼原因造成這個問題:編譯時
typedef struct{ /*Removed "item"*/
item *next; /*Removed "struct"*/
}item;
導致下列錯誤?它是否與我使用嵌套結構的事實有關?
謝謝。
編譯器不知道'item'是在聲明行'item * next'處。 –
沒有「嵌套結構」。不可能沒有無盡的遞歸。 – Olaf
對不起,我措辭不好。我不是指嵌套結構,而是嵌套別名。 –