Q: 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.
A: As in question 1.14, 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[footnote] , 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; };
See also question 1.14.
References:
K&R2 Sec. 6.5 p. 140
ISO Sec. 6.5.2.3
H&S Sec. 5.6.1 p. 132