Search code examples
cstructtrie

incompatible pointer types initializing initializing a basic trie node


I know C is very finnicky about file level initialization. Or rather I just don't know what constant expression means yet.

What I want to do is initialize a node (aka struct node) with all null pointers.

//Trie node definition
typedef struct node{
    bool is_word;
    struct node* next[27]; //27 for the valid number of chars

}node;


struct node* empties[27];
node empty = {.is_word = 0, .next = empties};

dictionary.c:24:33: error: incompatible pointer types initializing 'struct node *' with an
      expression of type 'struct node *[27]' [-Werror,-Wincompatible-pointer-types]
node empty = {.is_word=0,.next =empties};
                                ^~~~~~~
dictionary.c:24:33: error: suggest braces around initialization of subobject
      [-Werror,-Wmissing-braces]
node empty = {.is_word=0,.next =empties};

I'm getting an error when I try to initialize this. I would also try manually initializing the members but 27 indexes makes that very tedious. Is there a way to loop initialize at the file level?


Solution

  • Try node empty = {0, {0}};.

    This is an effective way to initialize structs and arrays, or as in this case, a struct containing an array.

    How to initialize all members of an array to the same value? has more on array initialization. But you can also embed the initializer into a struct, as shown here.