struct first_struct
{
int a;
int b;
};
struct second_struct
{
char d;
int e;
};
struct second_struct second_ins = {'a',10};
struct first_struct first_ins = {20,12};
int main()
{
struct second_struct *pointer = &first_ins;
printf("%d\n",pointer->d);
return 0;
}
And I get an output of 20. Basically, I was trying to see that if I declare a structure pointer, and try to point this to an instance of another structure, what result do I get. Besides a warning from compiler for an incompatible pointer type, it builds and runs fine. I was trying to understand how this operation was interpreted by compiler. Shouldnt this be undefined, or may be it is and I am just getting lucky with the result.
It's likely that both structs have the same element-wise alignment: sizeof(first_struct) == sizeof(second_struct)
and: int e
starts at the same offset in the struct as: int b
In other words, char d
is effectively stored as an int
in terms of layout. It's simply a lucky coincidence on your platform, and will not work portably.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With