Comment on Writing a C compiler in 500 lines of Python (2023)parentComments−threeducks1y9 lines seem to be sufficient (assuming string keys and int values). // Hashtable definition #include <string.h> #define N 1024 int* map_ptr(const char **keys, int *values, const char *key){ size_t h = 0, c = 0, i; for (const char *c = key; *c; c++) h = h * 33 + *(unsigned char*)c; for (i = h % N; c < N && keys[i] && 0 != strcmp(keys[i], key); i = (i + 1) % N, c++); if (!keys[i]) keys[i] = key; return 0 == strcmp(keys[i], key) ? &values[i] : NULL; } // Example usage const char *keys[N]; int values[N]; #include <stdio.h> int main(){ // Set some values *map_ptr(keys, values, "one") = 1; *map_ptr(keys, values, "two") = 2; *map_ptr(keys, values, "three") = 3; // Retrieve values printf("one: %i\n", *map_ptr(keys, values, "one")); printf("two: %i\n", *map_ptr(keys, values, "two")); printf("three: %i\n", *map_ptr(keys, values, "three")); return 0; }
Comments
9 lines seem to be sufficient (assuming string keys and int values).