c - 如何在c中初始化hashmap?

标签 c hashmap

我需要在 C 中初始化一个 hashmap。我已经为 hashnode 和 hashmap 创建了结构,如下所示,但我需要将其发送到函数

void hashmap_init(hashmap_t *hm, int table_size); 

我需要将 HashMap “hm”初始化为给定大小和 item_count 0。必须确保“table”字段初始化为大小为“table_size”的数组并用 NULL 填充。

typedef struct hashnode {  
char key[128];                
char val[128];                
struct hashnode *next;        
} hashnode_t;


typedef struct {  
int item_count;               
int table_size;               
hashnode_t **table;            
} hashmap_t;

#define HASHMAP_DEFAULT_TABLE_SIZE 5

最佳答案

使用 malloc() 分配 table_size 存储桶数组。

void hashmap_init(hashmap_t *hm, int table_size) {
    hm->item_count = 0;
    hm->table_size = table_size;
    hm->table = malloc(table_size * sizeof *(hm->table));
    for (int i = 0; i < table_size; i++) {
        hm->table[i] = NULL;
    }
}

如果您需要删除 HashMap ,请反转分配:

for (int i = 0; i < hm->table_size; i++) {
    free(hm->table[i]);
}
free(hm->table);

关于c - 如何在c中初始化hashmap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071218/

相关文章:

arrays - 将数组值映射到具有递增键名的散列

java - 使用键对 ArrayList/HashMap 进行排序

android - 如何在android中使用 Volley 发送ArrayList?

C:对于这个要求,有没有比 FIFO 队列实现更好的东西?

c - 如何限制只能输入一个字母?

c - 从文本文件中读取和存储未定矩阵

java - jsp中从hashmap中获取key和value

android - 理解 HashMap - 向 HashMap 中插入数据

c - C 应用程序中未处理的 win32 异常

c - fwprintf : only the first character from a wide char array argument gets copied to output