C++函数返回值未分配
C++ function returned value not assigned
我遇到了一个奇怪的错误
我正在返回一个指针,在返回之前,我验证了指针是否有效并且具有内存但是,在函数作用域之后,当我尝试在 main() 中使用返回值时,它变为 NULL。我还尝试返回指针的取消引用值,它是返回前修改的结构,并且是main()中未修改的结构。
这应该像字典
#include <iostream>
#include <fstream>
#include <string>
#include "trie.h"
using namespace std;
int alphaLoc(char segment){
return (int)segment - 97;
}
//inserts a word in the tree
void insert(TrieNode &node, const std::string &word){
int locationInAlphabet = alphaLoc(word[0]);
if (node.letters[locationInAlphabet] == NULL){
node.letters[locationInAlphabet] = new TrieNode;
}
if (word.length() == 1){
if (node.letters[locationInAlphabet]->isWord == true){
cout<<"Word Already Exsit"<<endl;
}
node.letters[locationInAlphabet]->isWord = true;
}
else{
insert(*(node.letters[locationInAlphabet]), word.substr(1,word.length()-1));
}
}
//returns the node that represents the end of the word
TrieNode* getNode(const TrieNode &node, const std::string &word){
int locationInAlphabet = alphaLoc(word[0]);
if (node.letters[locationInAlphabet] == NULL){
return NULL;
}
else{
if (word.length() == 1){
return (node.letters[locationInAlphabet]);
}
else{
getNode(*(node.letters[locationInAlphabet]), word.substr(1,word.length()-1));
}
}
}
int main(){
TrieNode testTrie;
insert(testTrie, "abc");
cout<< testTrie.letters[0]->letters[1]->letters[2]->isWord<<endl;
cout<<"testing output"<<endl;
cout<< getNode(testTrie, "abc")->isWord << endl;
return 1;
}
输出为:
1
testing output
Segmentation fault: 11
特里:
#include <string>
struct TrieNode {
enum { Apostrophe = 26, NumChars = 27 };
bool isWord;
TrieNode *letters[NumChars];
TrieNode() {
isWord = false;
for ( int i = 0; i < NumChars; i += 1 ) {
letters[i] = NULL;
} // for
}
}; // TrieNode
void insert( TrieNode &node, const std::string &word );
void remove( TrieNode &node, const std::string &word );
std::string find( const TrieNode &node, const std::string &word );
在getNode(*(node...
之前,您缺少return
。
如果此行在某个时刻执行,则在此执行控制流到达getNode
函数的末尾之后,此处没有return
语句。这将导致未定义的返回值,这总是不好的。您必须始终从函数中返回确定的内容。
相关文章:
- 将内存分配返回值强制转换为 TYPE 数组
- 如何删除新分配的字符,这也是函数返回值?
- 当设置对象等于另一个函数的返回值时,为什么要调用移动构造函数/分配
- 获取“将返回值分配给新变量”的警告和输出是内存地址
- 为循环中多次调用的函数返回值预分配内存的正确方法是什么
- 我可以分配成员访问操作员的返回值吗?
- 用户定义功能的返回值的分配:性能
- 分配从upper_bound到reverse_iterator的返回值
- 内存分配,用于在C 11中循环中函数的返回值:如何优化
- 分配操作员返回值类型
- 为什么将boost::move()的返回值分配给非常数引用在C++0x模式下失败,但在C++03模式下有效
- 如果我的C++“新”内存分配失败,如何找出返回值
- 函数在无法分配空间时返回值
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 当我调用函数而不将其返回值分配给变量时会发生什么
- 如何将实用程序 (grep/sed) 的返回值分配给数组
- C++函数返回值未分配
- C++ Visual Studio Express - 分配返回值失败功能
- 我们不必将函数的返回值分配给变量吗?C/C++
- C ++中新运算符的返回类型是什么?为什么我们可以将返回值分配给变量(非指针)?