将文本文件中的单词插入到C中的树中
Inserting word from a text file into a tree in C
这两天我遇到了一个奇怪的问题,我还没有解决。我正在尝试从 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");
}
}
如 link 帖子中所述,当我尝试将文本文件中的单词导入树中时,我得到 "Error Occured"。再次使用函数:
文本文件:
一个
啊啊
啊啊啊
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");
}
这证明树的功能工作正常,但我不明白发生了什么then.I我连续调试了 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];
更改为 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
元素。
似乎问题出在分配 strings.Strdup 似乎解决了问题!
这两天我遇到了一个奇怪的问题,我还没有解决。我正在尝试从 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");
}
}
如 link 帖子中所述,当我尝试将文本文件中的单词导入树中时,我得到 "Error Occured"。再次使用函数:
文本文件:
一个
啊啊
啊啊啊
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");
}
这证明树的功能工作正常,但我不明白发生了什么then.I我连续调试了 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];
更改为 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
元素。
似乎问题出在分配 strings.Strdup 似乎解决了问题!