2

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 its square root.

If I were writing javascript, I could just do this:

var squareRoots = {
   4: 2,
   9: 3,
   16: 4,
   25: 5
}

and then access them like:

var squareRootOf25 = squareRoots[5]

How do I do this in C? What if I want to use one type of enum as the key and another type of enum as the value?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
morgancodes
  • 25,055
  • 38
  • 135
  • 187

4 Answers4

3

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).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

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.

Community
  • 1
  • 1
Neera
  • 1,577
  • 8
  • 10
  • Short of writing a domain-specific language to generate C code or a resource file, you cannot reasonably specify a predefined lookup table at compile time, as the question seems to suggest is wanted. Even a sorted array to binary search is prone to ordering errors. +1 anyway, though, because that almost certainly doesn't matter. Just fill your data structure during your apps initialisation from a simple array of items. The run-time cost is rarely if ever an issue. The Javascript example effectively does this anyway, but with language-supplied container-filling code. –  Dec 29 '10 at 05:56
  • Run-time generation is just fine for my current needs. – morgancodes Dec 29 '10 at 06:10
1

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,
};
James M
  • 18,506
  • 3
  • 48
  • 56
tperk
  • 93
  • 2
0

You can use map implemented as part of clib library

Avinash
  • 12,851
  • 32
  • 116
  • 186