Selhar Selhar - 2 months ago 5
C Question

Why a structure is allowed to have "pointer to it's own type" as member but not "(an array of the) structure type" itself?

when i try to declare the following function

typedef struct TRIE_NODE
{
char* word;
struct TRIE_NODE node[26];
}TRIE_NODE;


I get the following error:


definition of 'struct TRIE_NODE' is not complete until the closing '}'


However, if i declare this function with a pointer to the 26 nodes, it compiles just fine.

typedef struct TRIE_NODE
{
char* word;
struct TRIE_NODE* node[26];
}TRIE_NODE;


I imagine that, since this is not an instance, it's impossible for me to get a pointer to the first of those 26 arrays, but if that is the problem, how is
TRIE_NODE* node[26]
not also a problem? Isn't this declaration equivalent to
TRIE_NODE node[1][26]
?

Answer

when i try to declare the following function

Wait!! that's not a function, that's typedef-ing a structure, a user-defined type.


That said, in the first case,

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE node[26];  //array of type struct TRIE_NODE
}TRIE_NODE;

if this has to be possible, compiler needs to know the size of the struct TRIE_NODE before it has been defined, which is impossible. So it is invalid.

On th other hand,

typedef struct TRIE_NODE
{
    char* word;
    struct TRIE_NODE* node[26];  //array of pointers (of type struct TRIE_NODE)
}TRIE_NODE; 

is fine, as you're allocating (array of) pointers to the structure, the actual size of the structure is not required to be known by compiler at that point. So, the compiler happily allocates the pointers and the definition (construct) is perfectly valid.

Comments