gpt4 book ai didi

C 哈希表问题,一切都具有相同的值(value)

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:16 26 4
gpt4 key购买 nike

出于某种原因,当我将元素插入哈希表时,同一索引处的所有元素最终都具有相同的值。例如,如果我在哈希表的索引 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 wordword 指针设置为指向同一个 word 数组(定义为局部变量的那个在函数中)。这个数组被文件中的每个单词覆盖,所以它们最终都是一样的。您需要为每个要保留的单词数组分配更多空间,并将其复制到那里。如果您将 strdup 函数更改为

,它会很好地为您做到这一点
w->word = strdup(word);

关于C 哈希表问题,一切都具有相同的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5697870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com