简体   繁体   English

如何在 C 中转发声明结构

[英]How to forward declare structs in C

I want to doubly link a parent to a child struct.我想将父母双重链接到子结构。 This I know works in C++.我知道这适用于 C++。

struct child;

struct parent{
   child* c;
} ;

struct child{
   parent* p;
} ;

, but in C with typedefs I can't make it work without warnings. ,但是在带有 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;
}

gives me warning: assignment to 'struct child *' from incompatible pointer type 'child *' .给我warning: assignment to 'struct child *' from incompatible pointer type 'child *' Is the first child struct then overwritten, or are there two distinct data structures now struct child and child ?然后是第一个子结构被覆盖,还是现在有两个不同的数据结构struct childchild

Is this even possible in C?这在 C 中是否可能? My second thought would be using a void* and cast it to child everywhere, but either option leaves a sour taste in my mouth so far.我的第二个想法是使用void*并将其投射到任何地方的孩子身上,但到目前为止,任何一种选择都会在我的嘴里留下酸味。

You can declare the structs then typedef them later:您可以声明这些结构,然后稍后对其进行 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;
}

The problem is that you have two different structures.问题是你有两种不同的结构。 The first one is第一个是

struct child;

and the second one is an unnamed structure with the alias name child第二个是别名为 child 的未命名结构

typedef struct {
    parent* p;
} child;

You need to write你需要写

typedef struct child {
    parent* p;
} child;

You can declare structures like this:您可以像这样声明结构:

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