Originally published on: Thu, 19 Nov 2009 02:35:02 +0000
I often need to use associative arrays when writing C code. You might be more familiar with these constructs under other names ( dictionaries, maps, hashmaps, hashes, …etc. ) I will use the term map in place of the words associative array.
A map is a collection of key / value pairs or name / value pairs. My implementation of a map structure allows strings as the only data that can be stored in the name and value.
Many implementations of maps use a hashed lookup to speed up execution. I have opted to use a simple forward-chained linked-list of map structures. When searching for an item in a map, the search will sequentially pass over every item in the list of map entries until a match is found. If no match is found, an empty string is returned.
This implementation is complete enough for my needs. See:
The test program map_stuff.c loads and displays a map with name/value pairs. The names are all numbers. The values are words that sound like the numbers ( homonyms ).
The output from the map_stuff program is as follows:
Two Too Four Fore One Won Two To Four Fore One Won Eight Eight Ate
I did not provide any kind of iterator functions in the library. If I need to iterate through a given map, I will just use a for-loop and will use the ->nxt element to reach each successive entry.