正在插入Trie,NULL指针
Inserting into a Trie, NULL pointers
我有一个关于Trie数据结构的特定问题,以及我的代码出了什么问题。当我递归调用insert时,函数参数root总是为NULL。这是我的代码:
代码:
//subNodes is an array of TrieNode pointers that contains indices for all letters in the alphabet
bool insert(const string& word, TrieNode* root, int curI = 0)
//PRE: word must be a valid word in a dictionary
//POST: True when a word is inserted into the Trie, false otherwise
{
if(curI >= word.length()) //word has been scanned fully
{
root->isWord = true;
return true;
}
else //word has more letters to be scanned
{
if(root->subNodes[word[curI] - 'A'] == NULL) //if the current letter of the word is not in the trie
{ // insert the letter and advance the current letter of the word
root->subNodes[word[curI] - 'A'] = new TrieNode(word[curI]);
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
else //if the currrent letter of the word is in the trie
{ // advance the current letter of the word
insert(word, root->subNodes[word[curI] - 'A'], curI++);
}
}
}
我通过用subNodes[word[13]]
替换subNodes[word[curI] - 'A']
来测试这一点(13
是字母表中N
的索引,而我测试的不是单词),并且该调用的根不再为NULL。因此,索引出现了问题。有人知道出了什么问题吗?我考虑过使用C++映射或向量。有人对使用数组有意见吗?
您的意思是++curl
吗?即将递增的值传递给递归调用?目前,由于curl++
是后增量的,所以您将相同的值传递到每个递归中。无论如何,只写curl + 1
可能更容易,因为您不再需要curl值。
这里有两个问题。
- 在两个序列点之间,如果变量被修改,则只能访问该变量以确定要存储的新值。在您的代码中,当您调用insert()时,curI会递增,并且还会被访问以作为参数传递。这是错误的
- C标准没有定义函数参数的评估顺序
http://en.wikipedia.org/wiki/Sequence_point
http://c-faq.com/expr/seqpoints.html
以下内容将解决此问题。
insert(word, root->subNodes[word[curI] - 'A'], curI);
curI++;
相关文章:
- 当使用通配符和null指针调用函数时,对输出的说明
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 将位数组转换为 HBITMAP 后 bmBits 的 NULL 指针
- 在访问类的树层次结构中的对象时避免使用 null 指针
- 排序时引用绑定到 'value_type' 类型的 null 指针
- NULL指针解决方案中的C 分割故障
- 取消引用会导致崩溃,即使对于非 NULL 指针也是如此,原因也是如此
- 跟进哈希表 C++,this->next = NULL 指针
- C++中的NULL指针
- 当删除NULL指针(C/C )时,可以保证SegFault
- 引用绑定到类型 'struct value_type' 的 null 指针
- 尝试在C++中使用 NULL 指针时不会发生分段错误
- if(NULL==指针)和if(指针==NULL)之间有什么区别
- 在Linux/GCC下,将NULL指针访问转换为C++异常
- NULL指针检查线程安全
- cppcheck null指针取消引用:m_buffer-否则,针对null进行检查是多余的
- strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记
- Null指针异常(int Vs char)
- 用户定义类中的Null指针无效
- 不是NULL指针,而是错误的访问错误消息