当尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的,也会出现“分段错误”错误。
editText
错误在这一行:
#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);
我无法理解为什么会发生这种情况,因为在上面的情况下,计算的散列位置将为20,散列表的大小为23。
解决问题的任何提示?提前谢谢。
答案 0 :(得分:0)
您应该为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;
}