[英]How to forward declare structs in C
我想將父母雙重鏈接到子結構。 我知道這適用於 C++。
struct child;
struct parent{
child* c;
} ;
struct child{
parent* p;
} ;
,但是在帶有 typedef 的 C 中,我無法在沒有警告的情況下使其工作。
struct child;
typedef struct {
struct child* c;
} parent;
typedef struct {
parent* p;
} child;
int main(int argc, char const *argv[]){
parent p;
child c;
p.c = &c;
c.p = &p;
return 0;
}
給我warning: assignment to 'struct child *' from incompatible pointer type 'child *'
。 然后是第一個子結構被覆蓋,還是現在有兩個不同的數據結構struct child
和child
?
這在 C 中是否可能? 我的第二個想法是使用void*
並將其投射到任何地方的孩子身上,但到目前為止,任何一種選擇都會在我的嘴里留下酸味。
您可以聲明這些結構,然后稍后對其進行 typedef:
struct child {
struct parent* p;
};
struct parent {
struct child* c;
};
typedef struct parent parent;
typedef struct child child;
int main(int argc, char const *argv[]){
parent p;
child c;
p.c = &c;
c.p = &p;
return 0;
}
問題是你有兩種不同的結構。 第一個是
struct child;
第二個是別名為 child 的未命名結構
typedef struct {
parent* p;
} child;
你需要寫
typedef struct child {
parent* p;
} child;
您可以像這樣聲明結構:
typedef struct parent {
struct child* c;
}parent;
typedef struct child {
parent* p;
}child;
int main(int argc, char const *argv[])
{
parent p;
child c;
p.c = &c;
c.p = &p;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.