【发布时间】:2019-05-17 05:32:07
【问题描述】:
我正在尝试使用以下代码编写一个非常简单的哈希表:
#include <stdio.h>
#include <string.h>
#define SIZE 10
typedef struct {
char *first_name;
char *last_name;
} Employee;
typedef struct {
Employee *table;
} Hashtable;
void initHashtable(Hashtable *ht) {
ht->table = (Employee *)calloc(SIZE, sizeof(Employee));
}
int hashKey(char *key) {
int length = strlen(key);
return length % SIZE;
}
void put(Hashtable *ht, Employee emp, char *key) {
int hashedKey = hashKey(key);
ht->table[hashedKey] = emp;
}
我可以通过以下方式插入元素:
int main(int argc, char const *argv[]) {
Employee e1;
e1.first_name = "John";
e1.last_name = "Doe";
Hashtable ht;
initHashtable(&ht);
put(&ht, e1, "Doe");
return 0;
}
但是我想修改“put”函数,所以当我尝试插入一些东西时,它会检查那个索引是否为空。如果为空,则返回一些消息,如果不是,则在该索引上插入。类似于:
void put(Hashtable *ht, Employee emp, char *key) {
int hashedKey = hashKey(key);
if (ht->table[hashedKey] != 0) {
printf("Employee is in that index!\n");
} else {
ht->table[hashedKey] = emp;
}
}
但是这个“if 语句”不起作用。所以,我尝试了 0 和 NULL。然后我尝试了像这样的投射:
if(ht->table[hashedKey] != (Employee *)0)
和
if(ht->table[hashedKey] != (Employee)0)
没有任何工作。我的问题是我知道 calloc 用 0、0 初始化。那么在 struct 的情况下 calloc 用什么初始化呢?
【问题讨论】:
-
我建议您将
table成员设置为 指针 数组。首先,它可以更轻松地解决您的问题,因为空条目将是NULL指针。其次,它还可以更轻松地解决另一个问题:哈希冲突,例如使用链接列表或类似的。 -
我正在尝试编译您的代码,我看到
invalid operands to binary expression ('Employee' and 'int')进行比较。也许这是个问题? -
@Someprogrammerdude 感谢您的建议,使用指针数组是个好主意。但是我仍然想知道在使用 struct 时 calloc 会初始化什么?
标签: c struct heap-memory dynamic-memory-allocation calloc