0

Why do I need to define a new Trienode in the following code as new TrieNode()? When I do it as new TrieNode, it gives a segmentation fault. Is there a default constructor for a struct datatype that's important to call here, if so what does it do?

struct TrieNode 
{
    struct TrieNode *children[ALPHABET_SIZE];
    bool isLeaf;
};
void insert(struct TrieNode *root, string key)
{
    for(int i=0; i<key.size(); i++)
    {
        if(root->children[key[i]-'a'] ==NULL)   root->children[key[i]-'a'] = new TrieNode();
        root = root->children[key[i]-'a'];
    }
    root->isLeaf = true;
        
}
4
  • 1
    Ask yourself: What values do children hold after you construct TrieNode? Commented May 10, 2024 at 23:25
  • 1
    There is a default constructor generated for you, but it doesn't do anything useful here. The compiler-generated default constructor default constructs all of the members, be the default for a pointer is to do nothing and leave the value uninitialized. But if you tell the array to zero initialize all of its members, TrieNode * children[ALPHABET_SIZE] = {};, life suddenly gets easier. Commented May 10, 2024 at 23:37
  • 1
    Note: In the above comment I left out struct. C++ learned a lot from C, and one of the things it learned was, "I know darn well that TrieNode is a struct, so why repeat it everywhere?" Commented May 10, 2024 at 23:39
  • NULL? C++ has nullptr, which is better in every way. Commented May 10, 2024 at 23:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.