Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中将文本文件中的单词插入到树中_C_File_Binary Search Tree - Fatal编程技术网

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

在C语言中将文本文件中的单词插入到树中,c,file,binary-search-tree,C,File,Binary Search Tree,在过去的两天里,我遇到了一个奇怪的问题,我还不能解决它。我试图从2个文本文件中获取单词,并将这些单词添加到树中。我选择的获取单词的方法如下: 我用于在树中插入单词的函数如下: void InsertWord(typosWords Words, char * w) { int error ; DataType x ; x.word = w ; printf(" Trying to insert word : %s \n",x.word ); Tree_Insert(

在过去的两天里,我遇到了一个奇怪的问题,我还不能解决它。我试图从2个文本文件中获取单词,并将这些单词添加到树中。我选择的获取单词的方法如下:

我用于在树中插入单词的函数如下:

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");
   }
}
正如在发布的链接中提到的,当我试图将文字从文本文件导入到树中时,我得到的是“出错”。再次说明该功能:


文本文件:

a


但当我用下面的方法插入完全相同的单词时,效果很好

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

for(i=0;i当您使用

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\u word[15];
更改为
char*this\u word;
,并将this\u word=malloc(15);
放在
的beging中,而不是`循环,使其为每次迭代分配一个新的缓冲区

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

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

我想我们需要查看
树插入()的源代码
。最好将字符串读入固定大小的缓冲区
此单词
,然后在
插入单词
中使用,如下所示:
x.word=strdup(w)
;谢谢你的回答,我现在就来试试!!让我们期待最好的结果,我应该在哪里更改它?我在时间之外做了,但仍然有相同的问题是的,时间之外不会有什么区别。用@MichaelWalz的建议来修复它。
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);
}