繁体   English   中英

如何在 C 中转发声明结构

[英]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 childchild

这在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM