【发布时间】:2019-11-22 21:40:55
【问题描述】:
我正在尝试将 (key, value) 对添加到哈希图中,但插入后无法访问这些值。
这个哈希表应该处理冲突,因为每当发生冲突时,我都会沿着每个哈希索引进行迭代。然后,当我到达该索引处的(键,值)对列表的末尾时,我将其插入。
本质上是一个基本的链表hashmap。
问题是,当我再次尝试访问该值时,我不断遇到分段错误(我的 showTable() 函数也失败了)。在这个测试中,我只是尝试在每个哈希索引处添加一些内容后访问每个哈希索引处的第一个(键,值)对。我可能正在做一些非常愚蠢的事情,但我看到了。
我还没有评论,但我希望代码是不言自明的。重要的是InsertKeyValuePair(),但我已经添加了所有内容,因为代码审查也将是有益的。
#include <stdlib.h>
#include <stdio.h>
typedef struct TVal KeyValue;
typedef struct TVal {
char *value;
char *key;
KeyValue *next;
} KeyValue;
typedef KeyValue **HashTable;
int MAX_SIZE = 200;
int HashKey(char *Key, int Max);
void InsertKeyValuePair(char *key, char *value, int Index, HashTable table);
int insert(char *Key, char *value, HashTable table, int size);
void showTable(HashTable table, int size);
int HashKey(char *Key, int Max) {
char c = *Key;
int Hash = 0;
int n = 1;
while (c != 0) {
Hash += n * ((int)c);
c = *(Key + n);
n++;
}
return Hash % MAX_SIZE;
}
void InsertKeyValuePair(char *key, char *value, int Index, HashTable table) {
KeyValue *cursor = *(table + Index);
while (cursor != NULL) {
cursor = cursor->next;
}
cursor = malloc(sizeof(KeyValue));
cursor->value = value;
cursor->key = key;
printf("insert <K,V>(%s,%s) HashIndex = %i\n", cursor->key, cursor->value, Index);
//Trying to access value previously inserted
KeyValue *cursor2 = *(table + Index);
printf("<K,V>(%s,%s)\n", cursor2->key, cursor2->value);
}
int insert(char *Key, char *value, HashTable table, int size) {
int Index = HashKey(Key, MAX_SIZE);
InsertKeyValuePair(Key, value, Index, table);
return size + 1;
}
void showTable(HashTable table, int size) {
int i;
for (i = 0; i < size; i++) {
KeyValue *cursor = *(table + i);
if (cursor == NULL)
continue;
while (cursor != NULL) {
printf("==============");
printf("<K,V>(%s,%s)\n", cursor->key, cursor->value);
cursor = cursor->next;
}
printf("==============");
}
}
int main() {
HashTable HTbl = malloc(sizeof(HashTable) * MAX_SIZE);
int size = 0;
size = insert("yeuydfdan", "wesfg", HTbl, size);
size = insert("ywere", "rdgg", HTbl, size);
size = insert("ye4", "3244", HTbl, size);
//showTable(HTbl, MAX_SIZE);
}
【问题讨论】:
-
您的
HTbl最终成为指向KeyValue的指针的指针。请解释你为什么这样设计。仔细检查您是否已为这三个级别中的每一个分配了内存。这会让你从这条赛道开始:ericlippert.com/2014/03/05/how-to-debug-small-programs -
@Yunnosch:
Htbl只是一个指向KeyValue的指针。 -
@alk 是它的类型(
Hashtable,是指向指针的指针),但是它被赋值为malloc的结果,它是(或应该被使用的)作为指针中使用的类型sizeof(),即Hashtable,即三重指针。或者换一种说法,应该是Hashtable* HTbl= malloc(sizeof(HashTable)*MAX_SIZE)才有意义。 -
ht.c:49:5:运行时错误:“struct KeyValue”类型的空指针内的成员访问
标签: c pointers linked-list hashtable singly-linked-list