将文本文件中的单词插入C语言的树中 [英] Inserting word from a text file into a tree in C
问题描述
在过去的两天里,我一直遇到一个奇怪的问题,但现在还无法解决.我正在尝试从2个文本文件中获取单词,并将这些单词添加到树中.我选择的获取单词的方法在这里引用: 将文本文件拆分为C .
I have been encountering a weird problem for the past 2 days and I can't get to solve it yet. I am trying to get words from 2 texts files and add those words to a tree. The methods I choose to get the words are refereed here: Splitting a text file into words in C.
我用来将单词插入树中的函数如下:
The function that I use to insert words into a tree is the following:
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");
}
}
如发布的链接中所述,当我尝试将文本文件中的单词导入树中时,出现发生错误".再次提供功能:
As mentioned in the link posted , when I am trying to import the words from a text file into the tree , I am getting "Error Occured". For once again the function:
文本文件:
a
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);
}
但是当我通过以下方式插入完全相同的单词时,它就可以正常工作.
But when I am inserting the exact same words with the following way , it works just fine.
for (i = 0 ; i <=2 ; i++)
{
if (i==0)
InsertWord(W,"a");
if (i==1)
InsertWord(W,"aaah");
if (i==2)
InsertWord(W,"aaahh");
}
这证明了树的功能可以正常工作,但是我不知道当时发生了什么,我已经连续调试了两天,但仍然无法弄清它.有什么想法吗?
That proves the tree's functions works fine , but I can't understand what's happening then.I am debugging for straight 2 days and still can't figure it. Any ideas ?
推荐答案
当您使用
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);
}
您总是在为字符串重复使用相同的内存缓冲区.这意味着您这样做
you are always reusing the same memory buffer for the strings. This means when you do
x.word = w ;
您始终存储相同的地址.而且每次读取都会重新定义所有已经存储的单词,从而基本上破坏了数据结构.
you are ALWAYS storing the SAME address. And every read redefine ALL already stored words, basically corrupting the data structure.
尝试将char this_word[15];
更改为char *this_word;
并放置一个this_word = malloc(15); in the beggining of the
while`循环,使其为每次迭代分配一个新的缓冲区.看起来像
Try changing the char this_word[15];
to char *this_word;
and placing a this_word = malloc(15);in the beggining of the
while` loop instead, making it allocate a new buffer for each iteration. So looking like
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)也解决了眼前的问题.
As suggested by Michael Walz a strdup(3) also solves the immediate problem.
当然,当树完成后,您还将释放.word
元素.
Of course you will also have do free up the .word
elements when finished with the tree.
这篇关于将文本文件中的单词插入C语言的树中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!