Why can't a struct be a member of itself?

后端 未结 3 1596
鱼传尺愫
鱼传尺愫 2021-01-23 03:24

I have a struct foo. Declaring a member of type foo* works:

typedef struct foo
{
    struct foo* children[26];
} foo;

3条回答
  •  -上瘾入骨i
    2021-01-23 03:55

    A structure T cannot contain itself. How would you know its size? It would be impossible to do so, because the size of T would require you to know the size of T (because T contains another T). This turns into an infinite recursion.

    You can have a pointer to T inside a structure T because the size of a pointer is not the same size as the pointed-to object: in this case, you would just store an address of memory where another T is stored - all the space you need to do that is basically the space you need to store a memory address where another T lives.

提交回复
热议问题