Are struct well defined in strict c 89?
I mean this code
struct a {
int a, b;
void * c;
} k;
//init k...
struct b {
int u, w;
long *data;
} p = *(struct b*)&k;
is going to work on every compiler that support the standard? If I reverse the cast (e.g. cast from struct b to struct a) c is going to be the same as the beginning?
I’m pretty sure it works with gcc(even with -ansi -pedantic), microsoft compiler and so on, but does it guarantee that it is standard c 89?
Thank you!
Don’t do this. Copy the fields manually:
Your code would most likely run just fine since
long *andvoid *will typically be identically implemented, but why risk it? The standard says stuff like:Note the last sentence, where pointers to “other types” (such as
long) are made distinct from pointers tovoid.The above is explicit, safe, and much clearer.