2012-06-13 140 views
1

我遇到了一个奇怪的错误C++函数的返回值

我返回一个指针,返回之前,我核实,指针是有效&有记忆 然而,功能范围,当我试图使用后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 

trie.h:

#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); 
+2

'getNode(*(node ...'? –

+0

@Riateche''''''''''''''')作为答案,我将删除我的 - 您的评论在我回答它的外观 – Fraser

+0

这是递归语句.. –

回答

3

您在getNode(*(node...之前缺少return

如果此行在某个时刻执行,则在此执行控制流程到达getNode函数的末尾,并且没有return声明在此处。这将导致未定义的返回值,这总是不好的。你必须总是从你的函数中返回一些确定的东西。

+0

no..it应该递归到字的最后一个字符 –

+0

这肯定是一个错误,如果这一行在某个时刻被执行,那么在这个执行控制流到达末尾之后''getNode'函数,并没有'return'语句在这里,它会导致未定义的返回值,这总是不好的,你必须总是返回你的函数确定的东西。 –