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

时间:2016-05-19 12:52:11

标签: c file binary-search-tree

过去两天我遇到了一个奇怪的问题,但我还是无法解决。我试图从2个文本文件中获取单词并将这些单词添加到树中。我选择获取单词的方法在这里被引用: Splitting a text file into words in 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”。再次功能:

文本文件:

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");
    }

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

2 个答案:

答案 0 :(得分:1)

当您使用

阅读单词时
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];更改为char *this_word;并放置this_word = malloc(15); in the beggining of the while循环,使其为每次迭代分配一个新缓冲区。所以看起来像

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个元素。

答案 1 :(得分:1)

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

相关问题