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

后端 未结 3 1589
鱼传尺愫
鱼传尺愫 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-23 03:57

    The structure Trie cannot contain another structure Trie in it , it will do a never - ending recursion but it may contain a pointer to another structure Trie

    So first one is correct

    typedef struct TRIE
    {
        bool is_endpoint;
        bool is_initialized;
        struct TRIE* children[26];
    } TRIE;
    
    0 讨论(0)
  • 2021-01-23 04:05
    1. Object of type T can't contains another non-static object of same type. If it may be possible, how to find size of that object? Size of pointer to object is always constant on current system.
    2. Check value of currentptr for non-NULL before you can access fields of currentptr (like is_endpoint).
    0 讨论(0)
提交回复
热议问题