String Hash Table Function for Associative Array in C Programming
The
String Hash Table program written in C is used to implement the associative array for the String values. In programming, Hash Table or Hash Map is a data structure that uses a hash function to map identifying values, known as keys such as person name, to their associated values like telephone number and other details. Thus, a hash table implements an associative array. The hash function is used to transform the key into the index, the hash of an array element where the corresponding value is to be required
Hash Table Implementation for String in C
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NHASH 29989 //Use a prime number!
#define MULT 31
struct node
{
char *word;
int count;
struct node * next;
} node;
typedef struct node Node;
Node *bin[NHASH];
unsigned int hash(char *p)
{
unsigned int h = 0;
for(; *p; p++)
h = MULT * h + *p;
return h % NHASH;
}
void incword(char *s)
{
Node * p;
int h = hash(s);
for(p = bin[h]; p!= NULL; p = p->next)
{
if(strcmp(s, p->word) == 0)
{
(p->count)++;
return;
}
}
p = (Node *)malloc(sizeof(node));
if(!p)
return;
p->count = 1;
p->word = (char *)malloc(strlen(s)+1);
strcpy(p->word, s);
p->next = bin[h];
bin[h] = p;
}
int main()
{
char buf[100];
for (int i=0; i<NHASH; i++)
bin[i] = NULL;
while(scanf("%s", buf) == 1)
incword(buf);
for (int i = 0; i < NHASH; i++)
for (Node * p = bin[i]; p != NULL; p = p->next)
printf("%s %d\n", p->word, p->count);
return 0;
}