Comment by somat
18 hours ago
Maps should be a first class type in every language.
I have this thing I want to do in C. Now my C is very weak so my plan was to do a prototype in python, keeping in mind the C ecosystem then sit down with my old copy of "The C Programming Language" and struggle through it. Doing it with no dicts was rough.
I am normally the sort to avoid adding any libraries I don't have to but if anyone has any hints to simple hash maps in C I am all ears.
My first recommendation is don't use C if you can avoid it. Rust, go, zig, nim, odin, c++ etc. have hashmaps built in to the standar library or the language itself, and will have other advantages over c as well.
If for some reason you absolutely need to use c, consider if you really need a hashmap. If your collection is relatively small, just use an array or linked list with linear search. That's a pattern I've seen used in several c codebases, I think because of the difficulty of using map types.
If linear search would be too slow, then a binary search tree is relatively easy to implement, and gives you log(n) lookup time (as long as it's balanced). Or if you build it up once and don't modify it very much afterwards, you can use a sorted array, with a binary search.
If you really need a hashmap, there are some implementations, but I've also seen a few c projects that just implement their own hashmaps.
you may try https://github.com/nothings/stb/blob/master/stb_ds.h. a single header implementation for both dynamic array and string based hash table
My suggestions, none of which are particularly simple but it's C, you get what you get with a language that doesn't even know what strings and arrays are:
0) use Lua with LuaJIT. It has very good C interop and native hashmaps. Downside - Lua has its own rough edges and LuaJIT is frozen at Lua 5.1 with some extensions for 5,2
1) SDL3 has a hashmap implementation with its properties API, and a general purpose hashmap that they're probably going to make public at some point maybe? Downside - overkill if you don't actually want to use the rest of the library.
2) https://github.com/tidwall/hashmap.c this seems to work fine and is the simplest hashmap implementation for C that I've seen. Downside - you still have to write a lot of boilerplate.