Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef'ed structs that have pointers to each other

Tags:

c

typedef

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?

like image 579
Gerald Senarclens de Grancy Avatar asked Sep 04 '11 19:09

Gerald Senarclens de Grancy


2 Answers

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 ?

like image 180
cnicutar Avatar answered Sep 28 '22 05:09

cnicutar


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

like image 32
Foo Bah Avatar answered Sep 28 '22 07:09

Foo Bah