【问题标题】:Inserting word from a text file into a tree in C将文本文件中的单词插入C中的树中
【发布时间】:2016-05-19 12:52:11
【问题描述】:

在过去的 2 天里,我遇到了一个奇怪的问题,我还不能解决它。我正在尝试从 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");
   }
}

正如发布的链接中所述,当我尝试将文本文件中的单词导入树时,我得到“发生错误”。再次使用函数:


文本文件:

一个

啊啊

啊啊啊


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 天,但仍然无法弄清楚。有什么想法吗?

【问题讨论】:

  • 我想我们需要看看Tree_Insert()的源代码。

标签: c file binary-search-tree


【解决方案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 thewhile` 循环,使其为每次迭代分配一个新缓冲区。所以看起来像

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

【讨论】:

  • 最好将字符串读入固定大小的缓冲区this_word,然后在InsertWord中使用strdup,如下所示:x.word = strdup(w) 。;
  • 谢谢你的回答,我现在就试试这个!!让我们期待最好的
  • 我应该在哪里更改它?我在一段时间之外做了,但仍然遇到同样的问题
  • 是的,在 while 之外没有任何区别。用@MichaelWalz 的建议解决这个问题。
【解决方案2】:

似乎问题出在字符串的分配上。Strdup 似乎解决了问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多