Someone
Someone

Reputation: 643

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];

Upvotes: 1

Views: 299

Answers (3)

Deepankar Chaudhary
Deepankar Chaudhary

Reputation: 33

One of the way to bypass the problem is passing 0 in place of NULL, since second parameter suppose to be a integer as per function prototype.

memset(children, 0, sizeof(children));

Refer to this in case confusion with 0 vs NULL: What is the difference between NULL, '\0' and 0?

Upvotes: 0

MSalters
MSalters

Reputation: 180050

The easiest C++ option is std::fill(std::begin(array), std::end(array), nullptr).

Upvotes: 1

Jarod42
Jarod42

Reputation: 218108

You might do:

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

    TrieNode() = default;
};

Upvotes: 3

Related Questions