Structure pointer pointing to an instance of another structure

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 the conclusion from 20. In principle, I tried to see that if I declare a structure pointer and try to point it to an instance of another structure, what result will I get. In addition to a warning from the compiler for an incompatible pointer type, it builds and works fine. I was trying to understand how this operation was interpreted by the compiler. Should it be undefined, or maybe it is, and I was just lucky with the result.

+5
source share
1 answer

It is likely that both structures have the same element alignment: sizeof(first_struct) == sizeof(second_struct) and: int e starts at the same offset in the structure as: int b

In other words, char d effectively stored as int in terms of layout. This is just a good match on your platform and will not work portable.

+2
source

Source: https://habr.com/ru/post/1210123/


All Articles