Monday, March 9, 2009

Declaring structure pointer

Suppose that you declare

struct x *xp;

without any definition of struct x. Is this legal? Under what circumstances would it be useful?

Answer: It is perfectly legal to refer to a structure which has not been "fleshed out," as long as the compiler is never asked to compute the size of the structure or generate offsets to any members. Passing around pointers to otherwise undefined structures is quite acceptable, and is a good way of implementing "opaque" data types in C.

No comments: