Created
May 26, 2013 09:54
-
-
Save wrl/5652278 to your computer and use it in GitHub Desktop.
k/v lists in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
/** | |
* this code has been placed into the public domain | |
*/ | |
/** | |
* ideally you'd have a hashmap (or lately i've been pretty happy with | |
* binary-trie-backed dicts), but in a pinch this sort of thing can be | |
* faster and is always simpler. | |
*/ | |
struct kvpair { | |
char *key; | |
void *value; | |
}; | |
struct kvpair pairs[] = { | |
{"k1", "value"}, | |
{"k2", "another value"}, | |
{"etc", "just goes on"}, | |
{NULL} | |
}; | |
/* equivalent to: */ | |
char *cpairs[] = { | |
"k1", "value", | |
"k2", "another value", | |
"etc", "just goes on", | |
NULL | |
}; | |
/***/ | |
void iter_over(struct kvpair *pairs) | |
{ | |
/** | |
* since pairs->value is a `void *` we'll just print the memory | |
* address as a hex number. the `z` format qualifier says `this number | |
* is a size_t`. | |
*/ | |
for (; pairs->key; pairs++) | |
printf("%s => %zX\n", pairs->key, (size_t) pairs->value); | |
} | |
int main(int argc, char **argv) | |
{ | |
puts("pairs:"); | |
iter_over(pairs); | |
puts(""); | |
puts("cpairs:"); | |
iter_over((struct kvpair *) cpairs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment