Skip to content

Instantly share code, notes, and snippets.

@mc1100
Created June 13, 2015 10:38
Show Gist options
  • Save mc1100/866cfb51ea2bc6bbf4b2 to your computer and use it in GitHub Desktop.
Save mc1100/866cfb51ea2bc6bbf4b2 to your computer and use it in GitHub Desktop.
Simple hashtable in C
#include "hash.h"
#include <stdlib.h>
static unsigned index(Hashtable *hashtable, void *key) {
unsigned i = (unsigned) key % hashtable->size;
while (hashtable->keys[i] && hashtable->keys[i] != key) {
if (++i >= hashtable->size) {
i = 0;
}
}
return i;
}
Hashtable *hashtable_create(size_t size) {
Hashtable *h = calloc(1, sizeof(Hashtable));
h->size = size;
h->keys = calloc(size, sizeof(void *));
h->values = calloc(size, sizeof(void *));
return h;
}
void hashtable_insert(Hashtable *hashtable, void *key, void *value) {
unsigned i = index(hashtable, key);
hashtable->keys[i] = key;
hashtable->values[i] = value;
}
void *hashtable_lookup(Hashtable *hashtable, void *key) {
return hashtable->values[index(hashtable, key)];
}
#pragma once
#include <stddef.h>
typedef struct {
size_t size;
void **keys;
void **values;
} Hashtable;
Hashtable *hashtable_create(size_t size);
void hashtable_insert(Hashtable *hashtable, void *key, void *value);
void *hashtable_lookup(Hashtable *hashtable, void *key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment