[英]C Hash Table Problem, Everything has same value
由于某种原因,当我将元素插入哈希表时,相同索引处的所有元素最终都具有相同的值。 例如,如果我在哈希表的索引2处有三个元素,那么这三个元素将与插入该索引的最后一个元素具有相同的“单词”。 我在插入之前为每个元素动态分配内存,所以我不知道问题所在。
有人知道吗? 谢谢。
struct word{
char *word;
struct word *next;
};
struct word *hashTable[20];
void func(const char *file)
{
char word[1000];
int i;
FILE *infile = stdin;
infile = fopen(file, "rb");
if(infile == NULL) {
printf("cannot open [%s]\n", file);
return;
}
while(fscanf(infile, "%s" word) != EOF) {
struct word *w;
w = malloc( sizeof( struct word ));
w->word = word;
w->next = NULL;
insert(w);
}
fclose (infile);
}
void insert(struct word *v)
{
if( hashTable[hash(v->word)] )
{
struct word *end = hashTable[hash(v->word)];
while(end->next != NULL ) {
end = end->next;
}
end->next = v;
}
else
hashTable[hash(v->word)] = v;
}
那是因为您将每个struct word
的word
指针设置为指向相同的word
数组(在func中定义为局部变量的一个)。 该数组将被文件中的每个单词覆盖,因此它们最终将都是相同的。 您需要为要保留的每个单词数组分配更多空间,然后将其复制到此处。 如果您将strdup
函数更改为
w->word = strdup(word);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.