There is no such thing as an associative array in the C programming language; there are only simple arrays and pointers to them with which a programmer can do things like static char *names[] = { "John", "Suzanne", NULL }; and then search for an entry by iterating over the (null-terminated) array and accessing one of its elements with printf("%s\\n", names[0]);

After using Perl and PHP for a while one gets used to associative arrays. In Perl, something like $surnames{'John'} = 'Doe'; allow the programmer to later print $surnames{'John'}; to retrieve the string "Doe".

The use of such maps (also called dictionnaries or hash tables) is desirable in C also. Apart from hsearch et.al, which suffer from a number of limitations, there are no functions to implement maps in the standard C library.

One very interesting and free library for implementing maps, is the set of routines published as Mapkit by Jean-Sebastien Roy. I've used mapkit a number of times now and greatly enjoy it. Documentation is a bit lacking, but the garden variety hacker will get the hang of it soon. I've created a small wrapper around the map functions (for strings anyway) which you are welcome to have for the asking. It allows me to do this:

MAP *surnames = map_new();

map_stash(surnames, "John", "Doe", 0);
map_stash(surnames, "Suzanne", "Delicious", 0);
...
printf("%s\\n", map_find(surnames, "Suzanne"));

Very practical.

Comments

blog comments powered by Disqus