Linux C 下的哈希表

/*
 * HashTest.c
 *
 *  Created on: 2012-7-10
 *      Author: root
 */


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

int main()
{
	printf("hashtest\n");
	struct hsearch_data *ht1 = (struct hsearch_data*)calloc(5, sizeof(struct hsearch_data));
	struct hsearch_data *ht2 = (struct hsearch_data*)calloc(5, sizeof(struct hsearch_data));
	struct hsearch_data *ht3 = (struct hsearch_data*)calloc(5, sizeof(struct hsearch_data));

	if(0 == hcreate_r(5, ht1) || 0 == hcreate_r(5, ht2) || 0 == hcreate_r(5, ht3))
	{
		printf("cannot create hashtable");
	}

	ENTRY e;
	ENTRY *ee;

	e.key = "e1";
	e.data = "e1data";
	hsearch_r(e, ENTER, &ee, ht1);

	e.key = "e2";
	e.data = "e2data";
	hsearch_r(e, ENTER, &ee, ht1);

	e.key = "e3";
	e.data = "e3data";
	hsearch_r(e, ENTER, &ee, ht2);

	e.key = "e4";
	e.data = "e4data";
	hsearch_r(e, ENTER, &ee, ht2);

	e.key = "e5";
	e.data = "e5data";
	hsearch_r(e, ENTER, &ee, ht3);

	ENTRY *eee;
	e.key = "e1";
	if (0 == hsearch_r(e, FIND, &eee, ht1))
		printf("cannot find entry\n");
	else
		printf("key: %s , value: %s .\n", eee->key, (char *)eee->data);

	e.key = "e2";
	if (0 == hsearch_r(e, FIND, &eee, ht1))
		printf("cannot find entry\n");
	else
		printf("key: %s , value: %s .\n", eee->key, (char *)eee->data);

	e.key = "e3";
	if (0 == hsearch_r(e, FIND, &eee, ht1))
		printf("cannot find entry\n");
	else
		printf("key: %s , value: %s .\n", eee->key, (char *)eee->data);

	e.key = "e4";
	if (0 == hsearch_r(e, FIND, &eee, ht2))
		printf("cannot find entry\n");
	else
		printf("key: %s , value: %s .\n", eee->key, (char *)eee->data);

	e.key = "e5";
	if (0 == hsearch_r(e, FIND, &eee, ht3))
		printf("cannot find entry\n");
	else
		printf("key: %s , value: %s .\n", eee->key, (char *)eee->data);

	hdestroy_r(ht1);
	hdestroy_r(ht2);
	hdestroy_r(ht3);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值