Alright, so here goes. I am trying to do a switch over a string value in C, as described here. However, the array of structs does not seem be initialised properly. My (simplified) program looks as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BADKEY -1
#define VALUE 1
#define OTHERVALUE 2
#define FOOVALUE 3
#define NREQKEYS (sizeof(lookuptable)/sizeof(symstruct_t))
typedef struct {
char *key;
int val;
} symstruct_t;
static symstruct_t lookuptable[] = {
{ "some value here", VALUE },
{ "other value", OTHERVALUE },
{ "yet another one", FOOVALUE }
};
int main(void) {
// Testing...
int i;
for (i = 0; i < NREQKEYS; i++) {
symstruct_t *sym = lookuptable + i * sizeof(symstruct_t);
printf("%d: key = '%s', val = %d.\n", i, sym->key, sym->val);
}
}
Then, I compile the above program as follows (it is saved in test.c
obviously), on Debian Jessie (currently testing). The version of gcc is gcc version 4.7.2 (Debian 4.7.2-5)
. Compiling gives no warnings or errors.
gcc test.c -o test -std=gnu99
Now, I would expect that this simple program simply prints out the values that I initialise the array with. However, the output is this:
$ ./test
0: key = 'some value here', val = 1.
1: key = '(null)', val = 0.
2: key = '(null)', val = 0.
The two possible causes I can think of are that either my loop is incorrect, which makes no sense to me, or that the initialisation somehow is wrong. However, searching this site and in general on Google did not help me. I am open to other solutions as well, but also interested in just why this does not work.
Thanks!