I am trying to create a trie, but when I initialize the pointers in the array to NULL it breaks the program. The program finishes but won't output anything. Why is it doing this I look at online examples and they are doing it.
class trie
{
private:
struct Node
{
char letter;
Node *children[26];
};
//the beginning of the trie
Node *root;
public:
/* Constructors with No Arguments */
trie(void);
/* Destructor */
~trie(void);
//Function to insert string into the trie.
void insert(string word);
//Function to help insert
void insertHelper(string word, Node * & trieNode);
//Funtion to print the contents of the trie.
void printTrie();
//Function to get the index if a char matches.
int getIndex(char letter);
};
trie::trie()
{
/* Initialize the root of the node */
root = NULL;
for(int i = 0; i < 26; i++){
root->children[i] = NULL;
}
}
trie::trie():root = NULL;and two lines laterroot->children. This is accessing a null pointer!root->children[i] = NULL;-- Problem is -- there is no root. Read your code carefully, as the issue is just two lines above the line in my comment. -- Why is it doing this I look at online examples -- That may explain the issue. You're looking at "online examples" and blind copying instead of actually learning what the code is doing.