I want to add a field to a structure in C. So for example I have the following structure.
struct A
{
some_type x;
some_type y;
}
I declare a
Yes, this would work, but only by accident.
If I recall the C99 standard correctly, this particular case is specifically required to work as you expect. But it's clear that this is only because sufficiently many people relied on it working before that, and it did work by accident in sufficiently many implementations, that the C99 standards committee felt obliged to legislate for it working de jure as well as de facto.
Don't let that tempt you into thinking that this is a good idea.
Anything which relies on standards edge-cases is permanently teetering on the edge of brokenness, because it looks hacky (and so makes your code's future readers uncomfortable) and looks clever (which makes them nervous of changing/fixing anything). Also it leads folk into making assumptions which, because you're already on the edge of what's legitimate, can tempt folk across the border into broken code. For example, the fact that the first element within the first sub-struct within a struct is aligned as you expect, does not imply that any other sub-elements are lined up. That fact that it works for your compiler does not imply that it'll work for anyone else's, leading to mind-bendingly confusing bugs.
Write:
A *a = &(b->a);
(as the comment above suggests) and your meaning is clear.
If for some obscure reason you have to cast B*
to A*
, then write a very clear comment explaining why you have no option but to do what you have to do, assuring the reader that it is legitimate, and pointing to the subsubsection of the C99 standard which licenses it.
If you really cannot find that subsection (and finding it is your homework/penance), then comment thus and I'll dig it up.