如何在c中声明2个结构相互包含

How to declare 2 structs contain each other in c

我正在为迷宫解决程序实现图形结构。我声明了 2 个结构:vertex 包含 label 来标记该顶点,edge 的 4 个方向; edge 包含 weight 和一个指向其他 4 个顶点的 vertex 指针。

extern struct graph
{
    int label;
    struct Edge up;
    struct Edge down;
    struct Edge left;
    struct Edge right;
}vertex;

extern struct Edge
{
    int weight;
    struct graph *neighbour;
}edge;

typedef struct graph vertex;
typedef struct Edge edge;

这种声明方式会导致一些错误:未知类型名称'vertex';字段 'up' 的类型不完整,..

(我试过extern但好像不是问题)

那么如何正确申报呢?

如有任何帮助,我们将不胜感激。

不确定为什么 graph 也是 Vertex,但您可以颠倒声明 2 个结构的顺序并使用前向声明。您还可以组合结构声明和类型定义。

struct graph;  // Forward declaration

typedef struct 
{
    int weight;
    struct graph *neighbour;
} edge;

typedef struct graph 
{
    int label;
    edge up;
    edge down;
    edge left;
    edge right;
} graph;