Skip to content

Instantly share code, notes, and snippets.

@wrl
Created May 26, 2013 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wrl/5652278 to your computer and use it in GitHub Desktop.
Save wrl/5652278 to your computer and use it in GitHub Desktop.
k/v lists in C
#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