Interview Questions

How can I define a pair of mutually referential structures?

C Interview Questions and Answers


(Continued from previous question...)

How can I define a pair of mutually referential structures?

How can I define a pair of mutually referential structures? I tried

typedef struct {
int afield;
BPTR bpointer;
} *APTR;

typedef struct {
int bfield;
APTR apointer;
} *BPTR;

but the compiler doesn't know about BPTR when it is used in the first structure declaration.

The problem lies not in the structures or the pointers but the typedefs. First, give the two structures tags, and define the link pointers without using typedefs:

struct a {
int afield;
struct b *bpointer;
};

struct b {
int bfield;
struct a *apointer;
};

The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. (struct b is ``incomplete'' at that point.) Occasionally it is necessary to precede this couplet with the empty declaration
struct b;
to mask the declarations (if in an inner scope) from a different struct b in an outer scope.
After declaring the two structures using struct tags, you can then declare the typedefs separately:
typedef struct a *APTR;
typedef struct b *BPTR;

Alternatively, you can define the typedefs before the struct definitions , in which case you can use them when declaring the link pointer fields:

typedef struct a *APTR;
typedef struct b *BPTR;
struct a {
int afield;
BPTR bpointer;
};

struct b {
int bfield;
APTR apointer;
};

(Continued on next question...)

Other Interview Questions