gpt4 book ai didi

c - 向 HashTable 插入时出错

转载 作者:行者123 更新时间:2023-11-30 16:31:51 27 4
gpt4 key购买 nike

当尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的,我也会收到段错误错误。

#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/

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