First of all, the C99 standard permits you to cast any struct pointer to a pointer to its first member, and the other way (6.7.2.1 Structure and union specifiers):
13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
In other way, in your code you are free to:
- Convert
B*
to A*
— and it will always work correctly,
- Convert
A*
to B*
— but if it doesn't actually point to B
, you're going to get random failures accessing further members,
- Assign the structure pointed through
A*
to A
— but if the pointer was converted from B*
, only the common members will be assigned and the remaining members of B
will be ignored,
- Assign the structure pointed through
B*
to A
— but you have to convert the pointer first, and note (3).
So, your example is almost correct. But useLikeB()
won't work correctly since aaa
is a struct of type A
which you assigned like stated in point (4). This has two results:
- The non-common
B
members won't be actually copied to aaa
(as stated in (3)),
- Your program will fail randomly trying to access
A
like B
which it isn't (you're accessing a member which is not there, as stated in (2)).
To explain that in a more practical way, when you declare A
compiler reserves the amount of memory necessary to hold all members of A
. B
has more members, and thus requires more memory. As A
is a regular variable, it can't change its size during run-time and thus can't hold the remaining members of B
.
And as a note, by (1) you can practically take a pointer to the member instead of converting the pointer which is nicer, and it will allow you to access any member, not only the first one. But note that in this case, the opposite won't work anymore!
struct aB
to include astruct sA
by value and not by pointer i.e. should bestruct sA a;