Why can't a struct have a member that is of the same type as itself?

后端 未结 4 610
谎友^
谎友^ 2020-12-18 03:44

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

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 04:20

    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.

提交回复
热议问题