Store known key / value pairs in c

I am currently studying c. I am writing a web server as an exercise.
Now I have to store status codes and phrases.

What is the best way to store these key / value pairs?

My first bet was a hashmap. But in c there is no built-in implementation. So I would have to use a library.

+7
source share
4 answers

Like the other answers, I would also recommend using an array of strings as a lookup table. If you assume that all status codes are unique, an array of strings is the easiest implementation for a smaller dataset.

As soon as you start storing large amounts of data, that is, when hashmaps become useful. The search array is the solution here, but as you said, you are learning C, you can actually implement the hash table in native C using dynamic memory (a critical concept for learning C.). This website explains how to create a hash table in C very well.

http://www.sparknotes.com/cs/searching/hashtables/section3.rhtml

+6
source

I would use a sorted array.

You can define an array in any order and sort it at runtime (once) using the qsort() function. You can then do binary queries using bsearch() . The total number of response codes is small, binary search will be very fast.

This has the advantage that you do not need external code for something simple.

+5
source

Here is an alternative idea that has the advantage of speed, having some memory overhead.

Basically, the simplest form of a hash table is where a hash function is an identifier (code → code), also known as a lookup table.

To do this, knowing that HTTP status codes are limited to 5xx, you can assume that 599 will be the highest you need, so you will create a table with 600 elements.

This table can be done as follows:

 const char * status_messages[600]; 

Initialization is quite simple:

 /* initialize all with NULL so invalid codes correspond to NULL pointers */ memset(status_messages, (int)NULL, 600 * sizeof(const char *)); /* ... */ status_messages[403] = "Forbidden"; status_messages[404] = "Not found"; /* ... */ 

Raising a message is also very simple:

 int code = 403; const char * message = status_messages[code]; 

This array will have a size of 2400 bytes (4800 on 64-bit platforms), but O (1) access time is guaranteed.

+5
source

Perhaps you can create a structure with K \ V in it.

Same:

 struct key_value { int key; char* value; }; struct key_value kv; kv.key = 1; kv.value = "foo"; 
+3
source

All Articles