-
Notifications
You must be signed in to change notification settings - Fork 3
/
hash_table_example.c
63 lines (52 loc) · 1.35 KB
/
hash_table_example.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* Author: NagaChaitanya Vellanki
*
* Hash table example
*/
#include <errno.h>
#include <search.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
ENTRY item;
ENTRY *found_item;
/* create hash table */
if(hcreate(3) == 0) {
printf("Error on hcreate, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
item.key = "1";
item.data = "foo";
hsearch(item, ENTER);
item.key = "2";
item.data = "bar";
hsearch(item, ENTER);
item.key = "3";
item.data = "goo";
hsearch(item, ENTER);
item.key = "4";
item.data = "bird";
// created a hash table of size 3, ideally entering a 4th item should
// return NULL but if it does not the system must have a created a hash
// table of bigger size for performance reasons
if(hsearch(item, ENTER) == NULL) {
printf("Erron on hsearch, %s\n", strerror(errno));
}
item.key = "2";
found_item = hsearch(item, FIND);
if(found_item != NULL) {
printf("key: %s, data: %s\n", found_item->key, (char *)found_item->data);
} else {
printf("key: %s was not found\n", item.key);
}
item.key = "5";
found_item = hsearch(item, FIND);
if(found_item != NULL) {
printf("key: %s, data: %s\n", found_item->key, (char *)found_item->data);
} else {
printf("key: %s was not found\n", item.key);
}
hdestroy();
exit(EXIT_SUCCESS);
}