Hallo,
I needed a simple hashtable, so I decided to test the included implementation.
I wrote a little test file to learn how it is used.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <search.h>
int main(int argc, char **argv)
{
_ENTRY *item, *ret;
char command, buffer[200];
item = malloc(sizeof(_ENTRY));
if (_hcreate(10)) do {
printf("\n[q]uit [i]nsert [f]ind : ");
while ('\n'==(command = getchar()));
switch (command) {
case 'i' : printf(" name : "); scanf("%s", buffer);
item->key = malloc(strlen(buffer)+1);
strcpy(item->key, buffer);
printf("phone : "); scanf("%s", buffer);
item->data = malloc(strlen(buffer)+1);
strcpy(item->data, buffer);
ret = _hsearch(*item, _ENTER);
if (ret) printf("\n> ok\n"); else printf("\n> ups\n");
break;
case 'f' : printf("name : "); scanf("%s", buffer);
item->key = buffer;
ret = _hsearch(*item, _FIND);
if (ret) printf("\n> %s -> %s\n", ret->key, (char *)ret->data);
else printf("\n> ups\n");
break;
case 'q' : _hdestroy();
break;
default : printf("?\n");
}
} while ( command != 'q' );
free(item);
return 0;
}
But it is not clear to me, how to free the key and data memory afterwards. May be I have not understand how to use this at all. Any hints?
czerny