[英]printing string-tri using trie.c and trie.h
這是我使用trie.c和trie.hi制作的主文件。 該程序的目的是存儲詞典文件中的單詞。
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
如您所見,我的insert方法適用於純字符串,例如“ zzz”,但我不知道為什么它不適用於從文件中提取的單詞。...您能幫我嗎?
我猜你的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);
這會將每個單詞存儲在單獨的緩沖區中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.