I am trying to accessing data from a global array of structs. However the following application crashes.
#include <stdio.h>
typedef struct {
char *fruit;
int score;
} t_fruitdata;
static t_fruitdata fruittable[] = {
{"Apple", 100},
{"Banana", 240},
{"Carrot", 40}
};
void main()
{
int table_len = sizeof(fruittable) / sizeof(t_fruitdata);
for (int i = 0; i < table_len; ++i)
{
t_fruitdata *fruitdata = fruittable + i*sizeof(t_fruitdata);
printf("At index %i fruit %s has a score of %i\n",
i,
fruitdata->fruit,
fruitdata->score);
}
}
Outputs:
At index 0 fruit Apple has a score of 100
[program terminates here]
I imagine I've stumbled into some undefined behavior? But I've seen this technique recommended on stack overflow before. I'm using cl
on windows to compile this with Visual Code 2017.