uthash针对不同的key类型,提供了不同的借口函数,需要开发者自己识别。本文介绍key为char数组类型时相关函数和用法。
```c
#define MAX_SLEN 10
/*
key为char数组类型Hash表举例
*/
typedef struct {
char iKey[MAX_SLEN]; //key值
char iValue[MAX_SLEN]; //value值
UT_hash_handle hh; //hash句柄,固定写法
} HashTable;
HashTable *add(HashTable *table, char *key, char *value) {
HashTable node = (HashTable)malloc(sizeof(HashTable));
strcpy(node->iKey, key);
strcpy(node->iValue, value);
HASH_ADD_STR(table, iKey, node);
return table;
}
HashTable *find(HashTable *table, char *key) {
if (table == NULL) {
return NULL;
}
HashTable *node;
HASH_FIND_STR(table, key, node);
return node;
}
//务必注意,del必须返回table,因为HASH_DEL是用宏实现的
HashTable *del(HashTable *table, char *key) {
HashTable *node = find(table, key);
if (node != NULL) {
HASH_DEL(table, node);
free(node