Hashmap

This is a simple hashmap for the C language that can be used to store data which holds a key and a value. It uses the djb2 hash function by Dan Bernstein.


Creating a new hashmap

Creating a new hashmap is really easy. It only requires the starting capacity which will be used for allocating the buckets (how many buckets) and calculating the hash.

hashmap* map = hashmap_create(20); // 20 buckets as the initial buckets

Adding data to a hashmap

With our newly created hashmap we can now give in a key and a value which will be a void pointer. This is due to there being no generic T in C and since a void pointer is able to hold any value we use that as a workaround.

hashmap_put(map, "test", (void*)"Hello world");

Retrieving data from a hashmap

Retrieving data from a hashmap is really easy since you just need to use the key which you assigned the value with.

char* test = (char*)hashmap_get(map, "test");
printf("%s", test); // "Hello world"

Removing data from a hashmap

Since we now know how to add and get data from our hashmap our next step will be removing data from a hashmap. This is just as simple, as getting a value in a hashmap since we just need the given in key.

hashmap* map = hashmap_create(20);
hashmap_put(map, "test", (void*)"Hello world");

char* test = (char*)hashmap_get(map, "test");
printf("%s\n", test); // "Hello world"

hashmap_remove(map, "test");

char* test2 = (char*)hashmap_get(map, "test");
printf("%d\n", test2 == NULL); // true (1)

Freeing the hashmap

Freeing the hashmap is also another important part of the hashmap library. Since it's manually allocated you also need to manually free it.

hashmap_clear(map);

Last updated