如何在 C 中转发声明结构

How to forward declare structs in C

我想将 link 加倍 parent 到 child 结构。我知道这在 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 *’。第一个 child 结构是否被覆盖,或者现在是否有两个不同的数据结构 struct childchild

这甚至可以用 C 语言实现吗?我的第二个想法是使用 void* 并将其投射到 child 任何地方,但到目前为止,这两种选择都让我觉得不爽。

您可以先声明结构,然后再对它们进行类型定义:

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;
}