尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的位置,我也会遇到分段错误错误。
#define initial_size 23
typedef struct user{
char nick[6];
char name[26];
}user;
typedef struct hashtable{
int size;
user **buckets;
}hashtable;
int elements = 0;
int size = initial_size;
hashtable * create() {
hashtable *htable = malloc(sizeof(htable));
htable->size = initial_size;
htable->buckets = calloc(initial_size, sizeof(htable->buckets));
return htable;
}
int hash(char *string) {
int hashVal = 0;
for( int i = 0; i < strlen(string);i++){
hashVal += (int)string[i];
}
return hashVal;
}
void insert(hashtable *HashTable, char *name, char *nick){
HashTable = resize_HashTable(HashTable);
int hash_value = hash(nick);
int new_position = hash_value % HashTable->size;
if (new_position < 0) new_position += HashTable->size;
int position = new_position;
while (HashTable->buckets[position] != 0 && position != new_position - 1) {
position++;
position %= HashTable->size;
}
strcpy(HashTable->buckets[position]->name, name);
strcpy(HashTable->buckets[position]->nick, nick);
HashTable->size = HashTable->size++;
elements++;
}
错误在以下行中:
strcpy(HashTable->buckets[position]->name, name);
strcpy(HashTable->buckets[position]->nick, nick);
使用此输入时:
int main(){
hashtable *ht = create();
insert(ht, "James Bond", "zero7");
return 0;
}
我不明白为什么会这样,因为在上述情况下,计算出的哈希位置将为20,哈希表的大小为23。
有解决问题的技巧吗?提前致谢。
最佳答案
您应该在create()函数中为每个存储桶分配内存。
hashtable * create() {
hashtable *htable = malloc(sizeof(htable));
htable->size = initial_size;
htable->buckets = calloc(initial_size, sizeof(htable->buckets));
int i;
for(i=0;i<initial_size;i++)
htable->buckets[i] = (user*)malloc(sizeof(user));
return htable;
}
关于c - 在HashTable中插入时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50425236/