简体   繁体   English

Typedef用于相互指向的结构

[英]Typedef'ed structs that have pointers to each other

Ansi C allows that two different structs can contain pointers to each other (also shown in structs-that-refer-to-each-other ). Ansi C允许两个不同的结构可以包含彼此的指针(也以结构形式显示 - 它们指向彼此 )。 I know that this is not a good idea in many circumstances, but that's not the question here. 我知道在许多情况下这不是一个好主意,但这不是问题。 Is it possible to achieve the same using typedef'ed structs? 是否有可能使用typedef'ed结构实现相同的?

The code below works just fine. 下面的代码工作得很好。

struct b;
typedef struct a {
    struct b *bb;
} A;
typedef struct b {
    struct a *aa;
} B;

But using type "B" it fails 但使用“B”型则失败了

typedef struct b B;
typedef struct a {
    B *bb;
} A;
typedef struct b {
    A *aa;
} B;

with

error: redefinition of typedef 'B' 错误:重新定义typedef'B'

Is it possible to tell the compiler that 'B' will be declared later and use it in the definition of A? 是否可以告诉编译器稍后将声明'B'并在A的定义中使用它?

You can do this instead: 你可以这样做:

typedef struct a A;
typedef struct b B;

struct a {
    B *bb;
};
struct b {
    A *aa;
};

Does this work for you ? 这对你有用吗?

The issue is that you already typedef'd it. 问题是你已经输入了它。

You should do something like this: 你应该做这样的事情:

struct a;
struct b;
typedef struct a A;
typedef struct b B;

And then you can define struct a and b and use a,b,A*,B* in the definitions of a and b 然后你可以定义struct a和b,并在a和b的定义中使用a,b,A *,B *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM