Why does “typdef struct { struct S *s; } S;” containing a pointer to same type compile?

后端 未结 3 1271
你的背包
你的背包 2020-11-29 09:28

I\'m trying to typedef a struct which contains a pointer to another of the same type.

Thats what I thought would be the best version:

3条回答
  •  独厮守ぢ
    2020-11-29 09:49

    To store a pointer to a struct, the compiler doesn't need to know its contents or size -- just the size of the pointer.

    In your first example, struct Element is an incomplete type until after the structure definition, but that works because you're only declaring a pointer to it and not an instance of the struct itself.

    In your second example, you don't declare a struct Element structure at all (struct Element and Element are not the same thing). Though you can still include the pointer in the structure, it does NOT refer to the same type, it refers to a struct Element that hasn't been defined. The struct definition in your typedef is an anonymous struct, so you'll be able to refer to it with Element (without the struct keyword) only. So the second example won't work as intended.

提交回复
热议问题