我的insert
函数出现段错误:
current->isWord = true;
一切编译正常,没有警告或错误 ( g++ -Wall -Wextra
)。我的main
函数只调用insert
一次函数,它不会工作。这是我的代码;它是我.h
和.cpp
文件之间的混合体:
const int alphabetSize = 26;
struct Node
{
bool isWord;
Node* child[alphabetSize];
};
Dictionary::Dictionary()
{
initNode(head); //Node* head; is defined in my .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 a new Node
void Dictionary::initNode(Node* current)
{
current = new Node;
current->isWord = false;
for (int i = 0; i < alphabetSize; i++)
{
current->child[i] = NULL;
}
}
//returns a pointer to the Node of the last character in the string
//isInsert tells it whether it needs to initialize new Nodes
Node* Dictionary::endOfString(string s, bool isInsert)
{
Node* current = head;
Node* next = head;
for (unsigned int i = 0; i < 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;
}