user22817
user22817

Reputation: 23

Two way struct pointer link, C

Is it possible to form a two way link between structs? I tried to achieve it like this:

typedef struct
{
    int foo;
    b *b;
} a;

typedef struct
{
    int bar;
    a *a;
} b;

But the struct a does not know what b is because it's declared afterwards.

Upvotes: 0

Views: 556

Answers (2)

VoidPointer
VoidPointer

Reputation: 3097

Try this,

typedef struct a a;
typedef struct b b;

struct a
{
    int foo;
    b *b;
} ;

struct b
{
    int bar;
    a *a;
} ;

Upvotes: 3

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

When you need to reference other structs that may have not been defined up until then, make your declaration like this and it should work:

typedef struct
{
    int foo;
    struct b *b;
} a;

typedef struct
{
    int bar;
    struct a *a;
} b;

Upvotes: 1

Related Questions