Associative arrays in C

ezpresso picture ezpresso · Feb 1, 2011 · Viewed 46.7k times · Source

I am implementing a way to transfer a set of data to a programmable dongle. The dongle is based on a smart card technology and can execute an arbitrary code inside. The input and output data is passed as a binary blocks that can be accessed via input and output pointers.

I would like to use an associative array to simplify the data processing code. Everything should work this way:

First the host application:

// Host application in C++
in_data["method"] = "calc_r";
in_data["id"] = 12;
in_data["loc_a"] = 56.19;
in_data["loc_l"] = 44.02;
processor->send(in_data);

Next the code inside the dongle:

// Some dongle function in C
char* method_name = assoc_get_string(in_data, "method");
int id = assoc_get_int(in_data, "id");
float loc_a = assoc_get_float(in_data, "loc_a");
float loc_l = assoc_get_float(in_data, "loc_l");

So my question is about the dongle part functionality. Is there C code or library to implement such an associative array behavior like the above?

Answer

Manuel Salvadores picture Manuel Salvadores · Feb 1, 2011

Glib's hash table. implements a map interface or (associative array). And it's most likely the most used hash table implementation for C.

GHashTable *table=g_hash_table_new(g_str_hash, g_str_equal);

/* put */
g_hash_table_insert(table,"SOME_KEY","SOME_VALUE");

/* get */
gchar *value = (gchar *) g_hash_table_lookup(table,"SOME_KEY");