C++ dictionary trie implementation -
i getting segfault in insert
function on line:
current->isword = true;
everything compiles fine no warnings or errors (g++ -wall -wextra
). main
function calls insert
function once , won't work. here code; hybrid between .h
, .cpp
file:
const int alphabetsize = 26; struct node { bool isword; node* child[alphabetsize]; }; dictionary::dictionary() { initnode(head); //node* head; defined in .h file under private: } bool dictionary::isprefix(string s) { node* current = endofstring(s, false); if (current == null) { return false; } else { return true; } } bool dictionary::isword(string s) { node* current = endofstring(s, false); if (current == null) { return false; } else { return current->isword; } } void dictionary::insert(string s) { node* current = endofstring(s, true); current->isword = true; //segfault here } //initializes new node void dictionary::initnode(node* current) { current = new node; current->isword = false; (int = 0; < alphabetsize; i++) { current->child[i] = null; } } //returns pointer node of last character in string //isinsert tells whether needs initialize new nodes node* dictionary::endofstring(string s, bool isinsert) { node* current = head; node* next = head; (unsigned int = 0; < s.length(); i++) { if (isalpha(s[i]) == true) { int letter = (tolower(s[i]) - 'a'); next = current->child[letter]; if (next == null) { if (isinsert == false) { return null; } initnode(next); current->child[letter] = next; } current = current->child[letter]; } } return current; }
initnode
creates new node
, initializes it, discarded. because current
passed value, when modified inside of function, changes not propagate outside of initnode
. straightforward fix make pass reference:
void dictionary::initnode(node*& current)
Comments
Post a Comment