2014-02-12 17 views
1

嘗試在C中構建樹。子節點必須包含在鏈表中。但是當我在struct treeNode的定義中使用「struct listNode *」時,listNode尚未聲明。那麼有什麼辦法可以首先聲明?或者無論如何解決這個問題?謝謝!用C構建一個通用樹(使用鏈表來保存子節點)

/*** Build a tree ***/ 
typedef struct treeNode { 
    char* target; 
    char* commands; 
    struct listNode* children; 
} tNode; 

/*** Build a linkedlist ***/ 
typedef struct listNode { 
    struct treeNode dependency; 
    struct listNode* next; 
} lNode; 

回答

4

使用所謂的前向聲明。所以,你的代碼看起來應該是這樣

/*** Build a tree ***/ 
struct listNode; 

typedef struct treeNode { 
    char* target; 
    char* commands; 
    struct listNode* children; 
} tNode; 

/*** Build a linkedlist ***/ 
typedef struct listNode { 
    struct treeNode dependency; 
    struct listNode* next; 
} lNode; 
1

前置以下到您的片段

struct listNode; 

這就是所謂的向前聲明。

此時沒有定義結構,但名稱是已知的,這是足夠的,因爲您只想引用它(使用指針),不包括它(這將需要知道其大小)。

請注意,您只能在尚未將要定義的類型使用指針的限制實際上是有道理的:它使

struct A { 
    struct B b; 
    int a; 
}; 

struct B { 
    struct A a; /* Uh, what's that? struct B contains struct A 
        * which contains struct B... Now what's the size 
        * of either of these structs? */ 
}; 

一個無效的結構(因爲它可以防止循環依賴)。

相關問題