C 在哈希表中插入时出错
当尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的,也会出现分段错误C 在哈希表中插入时出错,c,arrays,data-structures,segmentation-fault,hashtable,C,Arrays,Data Structures,Segmentation Fault,Hashtable,当尝试在哈希表中插入字符串时,即使哈希函数计算的位置是有效的,也会出现分段错误 #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; ha
#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++;
}
使用此输入时:
int main(){
hashtable *ht = create();
insert(ht, "James Bond", "zero7");
return 0;
}
我无法理解为什么会发生这种情况,因为在上面的例子中,计算的哈希位置是20,哈希表的大小是23
解决这个问题有什么建议吗?提前感谢。您应该为create()函数中的每个bucket分配内存
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;
}
hashtable*create(){
hashtable*htable=malloc(sizeof(htable));
htable->size=初始尺寸;
htable->bucket=calloc(初始大小,sizeof(htable->bucket));
int i;
对于(i=0;ibuckets[i]=(用户*)malloc(sizeof(用户));
返回htable;
}
可能是因为您没有为name
和nick
分配空间,只为指向它们的指针分配空间。要么是这样,要么是您分配存储桶的calloc已关闭。@fredrik我以前尝试过用malloc替换calloc,但错误不断发生,因此我认为它不会从那里发生。当您提到分配时name和nick的空格不是插入时使用的strcpy吗?您正在执行malloc(sizeof(htable))
这应该是malloc(sizeof(hashtable))
用hashtable*httable=(hashtable*)malloc(sizeof(hashtable));替换整行
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;
}