在 C 中转发声明一个结构体

Yan*_*ami 4 c struct forward-declaration

如何转发声明以下treeNodeListCell结构?

我尝试struct treeNodeListCell在结构定义之前编写,但代码无法编译。

有人有想法吗?

struct treeNodeListCell;

typedef struct _treeNode {
    treeNodeListCell *next_possible_positions;
} treeNode;

typedef struct _treeNodeListCell {
    treeNode *node;
    struct _treeNodeListCell *next;
} treeNodeListCell;
Run Code Online (Sandbox Code Playgroud)

use*_*109 5

可以转发声明 a struct,但是当您这样做时,您需要将struct关键字与转发声明struct标记一起使用。

struct _treeNodeListCell;

typedef struct _treeNode {
    struct _treeNodeListCell *next_possible_positions;
} treeNode;

typedef struct _treeNodeListCell {
    treeNode *node;
    struct _treeNodeListCell *next;
} treeNodeListCell;
Run Code Online (Sandbox Code Playgroud)

另一种选择是提前声明typedef。C允许你使用typedef不完整的类型,也就是说你可以typedef在定义结构之前先定义结构。这允许您在结构定义中使用 typedef。

typedef struct _treeNodeListCell treeNodeListCell;

typedef struct _treeNode {
    treeNodeListCell *next_possible_positions;
} treeNode;

struct _treeNodeListCell {
    treeNode *node;
    treeNodeListCell *next;
};
Run Code Online (Sandbox Code Playgroud)

如果您想使用问题中的结构而不更改它们,您只需要在typedef结构定义之前添加即可。

typedef struct _treeNodeListCell treeNodeListCell;

typedef struct _treeNode {
    treeNodeListCell *next_possible_positions;
} treeNode;

typedef struct _treeNodeListCell {
    treeNode *node;
    struct _treeNodeListCell *next;
} treeNodeListCell;
Run Code Online (Sandbox Code Playgroud)