Hafiz
Hafiz

Reputation: 4277

defining inter referential structures in C

If I will code some thing like following:

typedef struct {
    int a;
    PTR1 bpointer;
} *PTR2;

typedef struct {
    int b;
    PTR2 cpointer;
} *PTR1;

I am defining PTR1 after PTR2,but using if using it first then it will be may be compile time or runtime error. So how can I avoid any such error and use two referential structures? I think same is thing that we do in two interdependent classes. So is it possible that it will not show any error because we are just defining them at this time and at calling these both are already defined? Confuse a little bit.

I really appreciate your time to see my question and you effort.

thanks

Upvotes: 0

Views: 164

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215617

The first step is to get rid of the typedefs and use struct tags. Then you can forward-declare the struct tags, and make the typedefs separately if you still want to use them. Note that it's considered very very bad style to use typedef to define pointer-to-struct types, especially if there's no way to refer to the pointed-to type when you're finished.

struct struct1;
struct struct2;

struct struct2 {
    int a;
    struct struct1 *bpointer;
};

struct struct1 {
    int b;
    struct struct2 *cpointer;
};

Upvotes: 3

Related Questions