C Program to Implement String Hash Table Associative Array

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

#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 = (Node *)malloc(sizeof(node));
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)
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;

Related Topic How to Map Key to Value by Class Hashtable
A to Z Linux Commands quick reference sheet
PHP Functions for MySQL
How to Get URL Variables Function in Javascript
Useful Regular Expression Regex Syntax and Examples the Web Developer Need to Know

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback