[英]Forward declare a struct in C
快速提問,我如何轉發聲明以下treeNodeListCell
結構。
我嘗試在結構之前編寫struct treeNodeListCell
並且代碼仍然無法編譯。
有人有想法嗎?
struct treeNodeListCell;
typedef struct _treeNode {
treeNodeListCell *next_possible_positions;
} treeNode;
typedef struct _treeNodeListCell {
treeNode *node;
struct _treeNodeListCell *next;
} treeNodeListCell;
附言
這是我在 stackoverflow 上的第一個問題,所以請告訴我在寫問題方面我可以改進什么。
先感謝您:)
您可以轉發聲明一個struct
,但是當您這樣做時,您需要將struct
關鍵字與轉發聲明的struct
標簽一起使用。
struct _treeNodeListCell;
typedef struct _treeNode {
struct _treeNodeListCell *next_possible_positions;
} treeNode;
typedef struct _treeNodeListCell {
treeNode *node;
struct _treeNodeListCell *next;
} treeNodeListCell;
另一種方法是前向聲明的typedef
。 C 允許你typedef
一個不完整的類型,也就是說你可以在定義結構之前對結構進行typedef
。 這允許您在結構定義中使用 typedef。
typedef struct _treeNodeListCell treeNodeListCell;
typedef struct _treeNode {
treeNodeListCell *next_possible_positions;
} treeNode;
struct _treeNodeListCell {
treeNode *node;
treeNodeListCell *next;
};
如果您想使用問題中的結構而不更改它們,您所需要的只是結構定義之前的typedef
。
typedef struct _treeNodeListCell treeNodeListCell;
typedef struct _treeNode {
treeNodeListCell *next_possible_positions;
} treeNode;
typedef struct _treeNodeListCell {
treeNode *node;
struct _treeNodeListCell *next;
} treeNodeListCell;
您不能省略struct
中的結構。
你應該使用
struct treeNodeListCell *next_possible_positions;
代替
treeNodeListCell *next_possible_positions;
快速提問,我如何轉發聲明以下
treeNodeListCell
結構。
你不需要。
首先,您必須區分通過標簽識別結構類型和通過typedef
ed 別名識別它。 特別是,您需要了解typedef
是完全可選的。 在您使用它來定義結構類型的別名的地方,將typedef
聲明與結構聲明分開可能更清楚。
這是您沒有任何typedef
的聲明:
struct _treeNode {
struct _treeNodeListCell *next_possible_positions;
};
struct _treeNodeListCell {
struct _treeNode *node;
struct _treeNodeListCell *next;
};
以struct <tag>
形式表示的結構類型不需要前向聲明。
您也可以添加 typedef。 它們可以通過添加typedef
關鍵字和一個或多個標識符與上述定義相關聯,或者它們可以簡單地單獨編寫,如我之前建議的那樣:
typedef struct _treeNode treeNode;
typedef struct _treeNodeListCell treeNodeListCell;
就個人而言,我認為 typedef 被過度使用了。 我通常不會為我的結構和聯合類型定義typedef
別名。
但是,如果您真的想要這樣做,那么您可以聲明一個不完整類型的 typedef,例如尚未定義的結構類型。 這是一個常規聲明,而不是前向聲明,但它允許您在結構定義中使用別名,我認為這是您的目標:
typedef struct _treeNode treeNode;
typedef struct _treeNodeListCell treeNodeListCell;
struct _treeNode {
treeNodeListCell *next_possible_positions;
};
struct _treeNodeListCell {
treeNode *node;
treeNodeListCell *next;
};
事實上,從C11開始,你可以在同一個scope中編寫多個相同typedef
名稱的聲明,只要它們都定義名稱來標識相同的類型。 可以利用此規定來允許編譯問題中出現的 typedef / structure 聲明。 請注意,指定相同的類型並不要求以相同的方式表示該類型。 由於這應該是一個練習,因此我將留給您解決剩下的一些細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.