Skip to content

Instantly share code, notes, and snippets.

@semahawk
Created October 18, 2013 20:53
Show Gist options
  • Save semahawk/7048135 to your computer and use it in GitHub Desktop.
Save semahawk/7048135 to your computer and use it in GitHub Desktop.
A simple hash implementation.
/*
*
* hash.c
*
* A simple hash implementation.
*
* It's not mine, the credit goes to The Book.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* table entry */
struct nlist {
/* defined name */
char *name;
/* the whatever value */
int value;
/* next entry in the chain */
struct nlist *next;
};
#define HASH_SIZE 101
/* pointer table */
static struct nlist *hashtab[HASH_SIZE];
/* hash: form hash value for string <s> */
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASH_SIZE;
}
/* lookup: look for <s> in hashtab */
struct nlist *lookup(char *s)
{
struct nlist *np;
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
if (!strcmp(s, np->name))
/* found */
return np;
/* not found */
return NULL;
}
/* new: put (name, defn) in hashtab */
struct nlist *new(char *name, int value)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL){
/* not found */
np = malloc(sizeof(struct nlist));
if (np == NULL || (np->name = strdup(name)) == NULL){
return NULL;
}
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
np->value = value;
return np;
}
int main(void)
{
/* discard the returned values */
new("five", 5);
new("three", 3);
new("two", 2);
printf("five->value: %d\n", lookup("five")->value);
printf("two->value: %d\n", lookup("two")->value);
printf("three->value: %d\n", lookup("three")->value);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment