変なバグに遭遇した
ポインタを返しています。返す前に、ポインタが有効でメモリがあることを確認しましたが、関数スコープの後、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 );