教你從零開始寫一個雜湊表--雜湊表結構
阿新 • • 發佈:2018-12-16
我們的鍵-值對(items),每一個都會被儲存在結構體中:
// hash_table.h
typedef struct {
char* key;
char* value;
} ht_item;
我們的雜湊表儲存了一組鍵值對的指標,以及雜湊表大小的一些細節和它的填滿情況:
// hash_table.h
typedef struct {
int size;
int count;
ht_item** items;
} ht_hash_table;
初始化和刪除
我們需要為ht_item
定義初始化幻術。這個函式分配了ht_item
k
和v
的副本。把這個函式標記為static
,是因為它只會被雜湊表內部呼叫一次。
// hash_table.c
#include <stdlib.h>
#include <string.h>
#include "hash_table.h"
static ht_item* ht_new_item(const char* k, const char* v) {
ht_item* i = malloc(sizeof(ht_item));
i->key = strdup(k);
i->value = strdup(v);
return i;
}
ht_new
函式初始化了一個新的雜湊表。size
變數定義了我們可以儲存多少個鍵值對。此處寫死了53個。我們會在“重置大小”一節進行擴充套件。我們用calloc
函式初始化一組鍵值對。calloc
這個函式用NULL
對分配的記憶體進行填充。陣列的首位儲存是NULL
意味著這個桶是空的。
// hash_table.c
ht_hash_table* ht_new() {
ht_hash_table* ht = malloc(sizeof(ht_hash_table));
ht->size = 53;
ht-> count = 0;
ht->items = calloc((size_t)ht->size, sizeof(ht_item*));
return ht;
}
我們也需要函式來刪除ht_items
變數和ht_hash+tables
結構。這將會釋放我們已經分配的記憶體,不然就會導致記憶體洩漏。
// hash_table.c
static void ht_del_item(ht_item* i) {
free(i->key);
free(i->value);
free(i);
}
void ht_del_hash_table(ht_hash_table* ht) {
for (int i = 0; i < ht->size; i++) {
ht_item* item = ht->items[i];
if (item != NULL) {
ht_del_item(item);
}
}
free(ht->items);
free(ht);
}
我們已經寫完了定義雜湊表的程式碼。它讓我們可以建立和銷燬一個雜湊表。儘管它這個時候還做不了什麼事情,但我們依然可以試執行一下這份程式碼。
// main.c
#include "hash_table.h"
int main() {
ht_hash_table* ht = ht_new();
ht_del_hash_table(ht);
}
上一篇:教你從零開始寫一個雜湊表–導讀
下一篇:教你從零開始寫一個雜湊表–雜湊函式