Created
June 13, 2015 10:38
-
-
Save mc1100/866cfb51ea2bc6bbf4b2 to your computer and use it in GitHub Desktop.
Simple hashtable in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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