我正在尝试用 C 实现链式哈希表。这是类(class)中的一个项目,因此它不必是完美的,但我无法让它工作。
在我向哈希表添加新值的方法中,一切似乎都正常,但后来当我尝试在哈希表中查找某些值时,里面似乎什么也没有(或一些垃圾值)。我认为哈希函数工作正常,所以我不会发布它。相关代码如下:
// typedef a node for the linked list
typedef struct node
{
char* value;
struct node* next;
}
node;
// global variables
node* head = NULL;
node* lists[145000];
// this method inserts a new value into the hash table
bool insert_word(char* value, int index)
{
// inserting at the beginning of the list
node* new_node = malloc(sizeof(node));
new_node->value = value;
if (head == NULL)
{
head = new_node;
}
else
{
new_node->next = head;
head = new_node;
}
lists[index] = head;
return true;
}
// this method should check if the searched word
// is present in the hash table
bool check(const char* word)
{
int index = hash(word);
node* curr_node = lists[index];
while (curr_node != NULL)
{
if (strcmp(curr_node->value, word) == 0) // this never happens
{
return true;
}
curr_node = curr_node->next;
}
return false;
}
如果我能得到任何帮助,我将不胜感激,因为我已经为此苦苦挣扎了两天......谢谢:)
最佳答案
您正在分配一个新节点
node* new_node = malloc(sizeof(node));
new_node->value = value;
但是您没有测试 malloc
的失败并且您并不总是设置 next
new_node
的领域(因此,当 head
为 NULL
时,该字段可能包含垃圾)。
尝试类似的事情
node* new_node = malloc(sizeof(node));
if (!new_node) {perror("malloc node"); exit(EXIT_FAILURE); };
new_node->value = value; // probably needs:: strdup (value)
new_node->next = NULL;
最重要的是,使用所有警告和调试信息进行编译(例如,如果使用 GCC,则使用 gcc -Wall -g
)并学习如何使用调试器(例如 gdb
)。
还可以使用内存泄漏检测器,例如 valgrind ...
最后不知道insert_node
怎么样了叫?我猜(如 joop 评论)您可能想要复制该字符串,例如使用new_node->value = strdup(value);
关于c - C 中的哈希表实现 - 里面只有垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620761/