I\'m stuck on understanding what\'s happening with this struct (from C for Programmers
a Deitel book).
The book says, \"A structure cannot contain an
The magic here becomes clear when you understand the C concept of an incomplete type. A struct can only contain completed types, i.e. those that the compiler knows the size of. When the compiler sees
struct foo {
it knows that there will be a struct with the tag foo; this type (struct foo
) is incomplete at this very moment. It becomes complete not until the matching }
is seen.
However, and this is the magic, a pointer to an incomplete type is a complete type, because the size of any pointer is known--no matter what type it points to. So after the three tokens above, it is okay to declare a struct member
struct foo *ptr_to_struct_foo;
inside a struct foo
and before the matching }
.
Another often used incomplete type is void
--this type cannot even be completed, which is why C doesn't allow you to declare
void foo;
However, it is perfectly fine to declare pointers to such a type:
void *foo;
But indirecting through a ptr-to-void of course is not allowed. Why? Now you know the answer: because that would yield an incomplete type.