简体   繁体   中英

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 ). 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?

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

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

with

error: redefinition of typedef 'B'

Is it possible to tell the compiler that 'B' will be declared later and use it in the definition of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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