How does one construct and access a set of key-value pairs in C? To use a silly simple example, let\'s say I want to create a table which translates between an integer and i
You can use map implemented as part of clib library
You could consider hash implementation in C language to achieve this. For basics of hash refer to Wikipedia. Refer to this question for more details and links.
This link gives good overview and implementation details.
There is no built-in way to do this unless you count initializing an array like this in C99:
double squareRoots[] =
{
[4] = 2.0,
[9] = 3.0,
[16] = 4.0,
[25] = 5.0,
};
However, this allocates 26 elements in the array; the other values are all zeroes.
Assuming you didn't mean this, then look at C Interfaces and Implementations by D R Hanson; it shows a way of implementing associative arrays (aka hashes or dictionaries).
You could also use the libghthash for general purpose hashes. They are quite easy to use, and incorporate in your application. However, it is a third party API - so if that's a problem, you would have to implement your own.
There's no built in associate array/hash tables in C.
The array initialization (C99) is probably the best way to go unless you have non-numeric keys:
T hash[] = {
[1] = tObj,
[255] = tObj2,
};