C语言hashtabe 函数hsearch_r

函数原型

#include <search.h>

int hcreate(size_t nel);

ENTRY *hsearch(ENTRY item, ACTION action);

void hdestroy(void);

#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <search.h>

int hcreate_r(size_t nel, struct hsearch_data *htab);

int hsearch_r(ENTRY item, ACTION action, ENTRY **retval,
                     struct hsearch_data *htab);

void hdestroy_r(struct hsearch_data *htab);

typedef struct entry {
     char *key;
     void *data;
} ENTRY;

  • hcreate 和 hcreate_r 的参数是指 entry 的个数

  • 参数ACTION:

    • FIND // 忽略entry的data
    • ENTEN // insert a copy of item 插入一个拷贝的entry
  • 返回值:

    • 函数hsearch直接返回entry
    • 函数hsearch_r是通过retval指针返回

例子

#define _GNU_SOURCE
#include <stdio.h>
#include <search.h>
#include <stdlib.h>

int main()
{
    struct hsearch_data *htab = calloc(1, sizeof(struct hsearch_data));
    if (!htab) {
        printf("calloc fail\n");
        exit(0);
    }

    if (hcreate_r(10, htab) == 0){
        printf("hcreat_r fail\n");
        exit(0);
    }
    
    char *keys[] = {"key1", "key2", "key3"};
    char *data[] = {"yasuo", "kitty", "ruiwen"};
    //char data[] = "yasuo";

    // add 
    int i;
    for (i = 0; i < 3; i++){
        ENTRY e, *ep;
        e.key = keys[i];
        e.data = (void *) data[i];
        hsearch_r(e, ENTER, &ep, htab);
    }

    // search
    for (i = 0; i < 3; i++){
        ENTRY e2, *ep2;
        e2.key = keys[i];
        hsearch_r(e2, FIND, &ep2, htab);
        if (ep2 != NULL){
            printf("%s=%s\n", ep2->key, (char *)(ep2->data));
        }
    }
    hdestroy_r(htab);
    if (htab)free(htab);
    return 0;
}

修改KEY的data:

    char after[] = "modifyd";
    ENTRY e3, *ep3;
    e3.key = "key-test";
    e3.data = (void *)after;
    if (hsearch_r(e3, ENTER, &ep3, htab) == 0)
        printf("hsearch_r enter.key %s faild\n", e3.key);

    ENTRY *ep4 = &e3; 
    if (hsearch_r(e3, FIND, &ep4, htab)){
        if (ep4) {//如果找到直接修改ep4.data, 因为ep4指向e3,相当于修改了数据
            printf("%s=%s\n", ep4->key, (char *)(ep4->data));
            ep4->data = "wowowo";
        }
    }

    if (hsearch_r(e3, FIND, &ep4, htab)){
        if (ep4) printf("%s=%s\n", ep4->key, (char *)(ep4->data));
    }

输出

# ./a.out 
key-test=modifyd
key-test=wowowo

posted @ 2022-08-30 15:58  梦过无声  阅读(577)  评论(0编辑  收藏  举报