【问题标题】:C++ function returned value not assignedC++ 函数返回值未赋值
【发布时间】:2012-06-16 23:22:09
【问题描述】:

我遇到了一个奇怪的错误

我正在返回一个指针,在返回之前,我验证了该指针是有效的并且有内存 但是,在函数作用域之后,当我尝试使用 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 );

【问题讨论】:

  • returngetNode(*(node... 之前是否缺失?
  • @Riateche - 把这个作为答案,我会删除我的 - 你的评论在我回答之前就出现了。
  • 那是递归语句..

标签: c++ function return assign


【解决方案1】:

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

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

【讨论】:

  • no..它应该递归到单词的最后一个字符
  • 这里肯定是个错误。如果此行在某个时刻执行,则在此执行控制流到达getNode 函数的末尾之后,这里没有return 语句。它将导致未定义的返回值,这总是不好的。你必须总是从你的函数中返回一些明确的东西。
猜你喜欢
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多