Search code examples
c++data-structurestrieconstruction

How do I initialize all elements of TrieNodes' children to null


I am trying to solve a Trie problem, for which I create a TrieNode class as below:

class TrieNode {
    public:
    bool isWord;
    TrieNode* children[26];
    TrieNode() {
        isWord=false;
        memset(children, NULL, sizeof(children));    //results in warning
    };
};

This results in a warning:

warning: passing NULL to non-pointer argument 2 of 'void* memset(void*, int, size_t)' [-Wconversion-null]

Replacing it with nullptr results in a compile time error:

error: cannot convert 'std::nullptr_t' to 'int' for argument '2' to 'void* memset(void*, int, size_t)'

So my question is, how do I initialize all the values in children to NULL/nullptr? I tried a few options such as children[26]={ nullptr };, but those all resulted in runtime errors (worked fine only with memset(children, NULL, sizeof(children));).

Eventually, while building the trie, I wish to have the following logic:

if(!curr->children[index]) {
    curr->children[index]=new TrieNode();
}
curr=curr->children[index];

Solution

  • You might do:

    class TrieNode
    {
    public:
        bool isWord = false;
        TrieNode* children[26]{};
    
        TrieNode() = default;
    };