Simplified example:
typedef union {
int foo;
char* bar;
} int_or_str;
void baz() {
int_or_str* bogus = malloc(sizeof(int_or_str) * 43);
bogus[42].bar = "test";
printf("%s\n", bogus[42].bar);
}
- Should this work, will the compiler assume all 42 members of
bogus
are char pointers? (Obviously, I could try this, but emphasis on "should"). - Is it even defined what happens when you access an array of unions in such a way?
- Suppose, I wanted an array of unions which actually hold differently sized values, is it legal? (I could store a layout separately, and compute the offset, if I was sure how union members are laid out in memory).
If you are wondering about motivation for this question: basically, I'm trying to come up with a solution for a run-time defined struct. My idea was to have an array of unions to represent struct fields, plus some meta-data recording how to access those fields.