- 求职 : 数据库管理员
- 论坛徽章:
- 0
|
source如下
gnuhash.h
- #ifndef _GUN_HASH_LIST
- #define _GNU_HASH_LIST
- #include <string.h>
- #define __USE_GNU
- #include <search.h>
- #define hash_create(size, tab) do { \
- int len = sizeof(struct hsearch_data); \
- tab = malloc(len); \
- memset(tab, 0, len); \
- hcreate_r(size,tab); \
- } while (0)
- #define hash_createa hcreate_r
- #define hash_destory hdestroy_r
- ENTRY *hash_add(char *key, void *value, struct hsearch_data *tab)
- {
- ENTRY item, *ret ;
- item.key = key ;
- item.data= value ;
- int x= hsearch_r(item, ENTER, &ret, tab);
- return ret ;
- }
- ENTRY *hash_find(char *key, struct hsearch_data *tab)
- {
- ENTRY item, *ret ;
- item.key = key ;
- int x= hsearch_r(item, FIND, &ret, tab);
- return ret ;
- }
- ENTRY *hash_addentry(ENTRY item, struct hsearch_data *tab)
- {
- ENTRY *ret ;
- int x = hsearch_r(item, ENTER, &ret, tab);
- return ret ;
- }
- ENTRY *hash_findentry(ENTRY item, struct hsearch_data *tab)
- {
- ENTRY *ret ;
- int x= hsearch_r(item, FIND, &ret, tab);
- return ret ;
- }
- #endif
复制代码
test.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "gnuhash.h"
- void prtht(ENTRY *ret)
- {
- printf("%9.9s->%s\n",
- ret ? ret->key : "NULL",
- ret ? (char *)(ret->data) : "");
- }
- int main(int argc ,char **argv) {
- ENTRY e, *ret;
- int i ;
- struct hsearch_data *ht ;
- hash_create(5, ht);
- printf (" key->value\n") ;
- ret = hash_add("test1", "aaa", ht) ;
- prtht(ret) ;
- ret = hash_add("test2", "bbb", ht) ;
- prtht(ret) ;
- ret = hash_add("test3", "ccc", ht) ;
- prtht(ret) ;
- ret = hash_add("test1", "ddd", ht) ;
- prtht(ret) ;
- printf("\nfind\n") ;
- ret = hash_find("test1", ht) ;
- prtht(ret) ;
- hash_destory(ht) ;
- return (EXIT_SUCCESS);
- }
复制代码
編譯:
gcc -g -pipe -o test test.c
運行結果如下:
- key->value
- test1->aaa
- test2->bbb
- test3->ccc
- test1->aaa
- find
- test1->aaa
复制代码
問題是 :第二次輸出test1值該為"ddd"
請各位幫忙
[ 本帖最后由 gangjh 于 2006-6-16 10:14 编辑 ] |
|