将文本文件中的单词插入到C中的树中

在过去的两天里,我遇到了一个奇怪的问题,但我还是无法解决它。 我试图从2个文本文件中获取单词并将这些单词添加到树中。 我选择获取单词的方法在这里被引用: 将文本文件拆分为C中的单词 。

我用来将单词插入树中的函数如下:

void InsertWord(typosWords Words, char * w) { int error ; DataType x ; x.word = w ; printf(" Trying to insert word : %s \n",x.word ); Tree_Insert(&(Words->WordsRoot),x, &error) ; if (error) { printf("Error Occured \n"); } } 

正如发布的链接中所提到的,当我尝试将文本文件中的单词导入树中时,我收到“Error Occured”。 再次function:


文本文件:

一个

AAAH

aaahh


 char this_word[15]; while (fscanf(wordlist, "%14s", this_word) == 1) { printf("Latest word that was read: '%s'\n", this_word); InsertWord(W,this_word); } 

但是当我按照以下方式插入完全相同的单词时,它的工作正常。

  for (i = 0 ; i <=2 ; i++) { if (i==0) InsertWord(W,"a"); if (i==1) InsertWord(W,"aaah"); if (i==2) InsertWord(W,"aaahh"); } 

这certificate了树的function正常,但我无法理解当时发生了什么。我正在调试直接2天仍然无法弄清楚。 有任何想法吗 ?

当你阅读使用的单词时

 char this_word[15]; while (fscanf(wordlist, "%14s", this_word) == 1) { printf("Latest word that was read: '%s'\n", this_word); InsertWord(W,this_word); } 

你总是为字符串重用相同的内存缓冲区。 这意味着当你这样做

 x.word = w ; 

你总是存储相同的地址。 每次读取都会重新定义所有已存储的单词,基本上会破坏数据结构。

尝试更改char this_word[15]; to char *this_word; 并放置一个this_word = malloc(15); in the beggining of the while循环in the beggining of the ,使它为每次迭代分配一个新的缓冲区。 所以看起来像

 char *this_word; while (fscanf(wordlist, "%14s", this_word) == 1) { this_word = malloc(15); printf("Latest word that was read: '%s'\n", this_word); InsertWord(W,this_word); } 

正如Michael Walz所建议的那样,strdup(3)也解决了当前的问题。

当然,完成树之后你也可以释放.word元素。

似乎问题是在strings.Strdup的分配似乎解决了问题!