我得到段錯誤在我insert
上線功能:C++詞典索引樹實現
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;
}
爲什麼在insert()中沒有NULL檢查? – iammilind 2013-04-09 03:51:58
@iammilind:因爲它像其他時間一樣將'true'傳遞給'endOfString'而不是'false'。 – icktoofay 2013-04-09 03:52:45
@icktoofay,如果在'Dictionary :: endOfString(..)'方法中'head'爲NULL並且s.length()= 0,會發生什麼?我們還需要在這種情況下進行NULL檢查。 – iammilind 2013-04-09 03:57:32