gpt4 book ai didi

c - 如何在 C 中声明依赖结构?

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:07 25 4
gpt4 key购买 nike

我需要声明一个相互使用的结构。例如,我该如何编译它?

z3 src # cat dependant.h
typedef struct egg_t egg_t;
typedef struct chicken_t chicken_t;

typedef struct egg_t {
int egg_num;
struct chicken_t chicken;
} egg_t;

typedef struct chicken_t {
int chicken_num;
struct egg_t egg;
} chicken_t;
z3 src # gcc -c dependant.h
dependant.h:6:20: error: field 'chicken' has incomplete type
dependant.h:7:3: error: redefinition of typedef 'egg_t'
dependant.h:1:22: note: previous declaration of 'egg_t' was here
dependant.h:12:3: error: redefinition of typedef 'chicken_t'
dependant.h:2:26: note: previous declaration of 'chicken_t' was here
z3 src #

最佳答案

您可以创建指向不完整类型的指针(取消 typedef,因为它们不添加任何内容):

struct egg_t;
struct chicken_t;

struct egg_t {
int egg_num;
struct chicken_t *chicken;
};

struct chicken_t {
int chicken_num;
struct egg_t *egg;
};

当然,正确的答案是首先避免这种循环依赖,但这并不总是可行的。

关于c - 如何在 C 中声明依赖结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com