2013-11-27 93 views
-1

我有這個二叉樹,其中每個結構,讓我們調用它們A有另一個結構類型的指針,讓我們調用它們B,指向另一個結構類型B等等形成一個結構類型B)的鏈表。從不兼容的指針類型/ deref指向不完整類型的指針

圖片:

(A) 
/\ 
(A)->(B)->(B)->(B)->|| 

的問題,我不知道。我收到一個錯誤,指出:

AddRemove.c: In function ‘AddRemove’: 
AddRemove.c:21: warning: assignment from incompatible pointer type 
AddRemove.c:22: error: dereferencing pointer to incomplete type 
AddRemove.c:23: error: dereferencing pointer to incomplete type 
AddRemove.c:24: error: dereferencing pointer to incomplete type 
AddRemove.c:26: error: dereferencing pointer to incomplete type 

代碼:

struct A{ 
//other variables 
struct A *left,*right; 
struct B *queue;   
}*rootT; 

struct B{ 
//other variables 
struct B *next; 
}; 

void AddRemove(struct A *aNode, struct B *bNode){ 
/*aNode is the memory location of the struct node (A) in the picture and bNode is 
a struct node that we want to add to the linkedlist.*/ 
struct B *Bptr; //Used to go through the linkedlist of struct type B 
if(aNode->queue==NULL){ /*If the pointer of node (A) is null then we have the 
pointer point to bNode, the node that we wanted to add.*/ 
    aNode->queue=bNode; 
    bNode->next=NULL; 
} 
else{ 
    Bptr=aNode->queue; /*Otherwise have the temp pointer point to what 
node (A)'s pointer points to, which should be the first struct type (B)*/ 
    while(Bptr->next!=NULL){ /*Keep pointing to the next struct of type B until 
we hit the end*/ 
     Bptr=Bptr->next; 
    } 
    Bptr->next=bNode; 
} 
} 
+0

在定義struct A之前添加聲明:'struct B;' –

+0

這並沒有改變我收到的錯誤。我應該提到這些結構聲明是在一個單獨的.h文件中。 – user2644819

+1

你是否在這個源代碼中包含頭文件?如果沒有,你需要這樣做。如果您不將它們包含在翻譯單元中,編譯器將無法對這些類型進行任何處理。 –

回答

1

缺少分號:

struct B{ 
    //other variables 
    struct B *next; 
}; 
^ 

此外,由於您使用的是結構的定義裏面不完全類型,你應該使用typedef

typedef struct A A; 
typedef struct B B; 

struct A { 
    //other variables 
    A *left,*right; 
    B *queue;   
} *rootT; 

struct B { 
    //other variables 
    B *next; 
}; 
+1

如果分號丟失,編譯器會給出不同的錯誤。按照最初寫入的方式在指針中使用'struct A'和'struct B'是完全允許的;沒有強制要使用你顯示的'typedef's。儘管Linux內核不使用它們,但它們是一個好主意(所以不是每個人都同意)。但是,您需要清楚'必須改變'和'可以/應該改變'之間的區別。你確實說'應該',但你沒有真正解釋。 –

+0

也許我在吠叫錯誤的樹。我認爲這是必需的,當你從另一個引用一個,但也許只有當它是相互交叉引用時。我希望你的頭沒有被包括在內。 – paddy

+1

如果'struct X'引用在文件範圍內(不在函數內部;不在函數原型中),那麼基本上你可以在任何地方提及'struct X',它表明結構類型爲'struct X',你可以使用它來定義指向該類型的指針,而不需要任何進一步的細節。要定義'struct X'類型的實際變量,必須提供完整類型。 'typedef'名稱和結構標籤都有作用域。 _ [... continue ...] _ –