2017-05-11 7 views
0

これはtrie.cとtrie.hを使った私のメインファイルです。このプログラムの目的は、辞書ファイルから単語を保存することです。trie.cとtrie.hを使って文字列をトリミングする

node* x = (node*)malloc(sizeof(node)); 
x = insert("bb", x); 
x = insert("sdf", x); 
x = insert("df", x); 
x = insert("bbbb", x); 
printAllWords(x); 

。 。 。 。 。

 while (fgets(word, MAX_WORD, file) != NULL) { 
      if (word[strlen(word)-1] == '\n') { // remove '/n' at the last 
       word[strlen(word)-1]='\0'; 
      } 
      printf("print word : %s \n" , word); 
      printf("length : %d \n" , (int) strlen(word)); 
      dictionary = insert(word, dictionary); 
     } 
     dictionary = insert("PLEASE", dictionary); 
     dictionary = insert("zzz", dictionary); 
     printAllWords(dictionary); 

。 。 。 。

と私の出力が

bbbb 
bb 
df 
sdf 
print word : he 
length : 2 
print word : he's 
length : 4 
print word : halp 
length : 4 
print word : hapless 
length : 7 
print word : hello 
length : 5 
PLEASE 
hello 
hello 
hello 
hello 
hello 
zzz 

でご覧のとおり、私の挿入方法は、「ZZZ」として、純粋な文字列で動作しますが、それはファイルから抽出した単語では動作しない理由を私は知りません。 ...手伝ってくれませんか?

+1

私の推測では、文字列へのポインタを格納していて、それをあなたの挿入メソッドにコピーしていないと思います。文字列のコピーをトライに保存する必要があります。あなたのコードを投稿していないので、それは唯一の推測です。しかし、あなたの出力と使い方から、ループインサートに 'word'へのポインタを格納しています。 – pstrjds

+1

'dictionary = insert(word、dictionary);' - > 'dictionary = insert(strdup(word)、dictionary);' – BLUEPIXY

答えて

0

私はあなたのnodeが似ていることを推測します:

struct 
{ 
    char *word; 
    // Left and right pointers, etc 
} node; 

そしてinsert(char const *newWord)があります

thisNode->word = newWord; 

を使用すると、ポインタ代入に従った場合は、すべての新しい単語を自分のループポイントで同じメモリアドレスに。迅速かつ汚い修正は次のとおりです。

struct 
{ 
    char word[MAX_WORD_LENGTH]; 
    // Left and right pointers, etc 
} node; 

そしてinsert(char const *newWord)があります

strcpy(thisNode->word, newWord); 

これは、別のバッファ内の各単語を格納します。

+0

ありがとうございます! –

関連する問題