Consider the following two struct
:
struct a
{
int a;
};
struct b
{
开发者_如何学运维 struct a a_struct;
int b;
};
the following instantiation of struct b
:
struct b b_struct;
and this condition:
if (&b_struct == (struct b*)&b_struct.a_struct)
printf("Yes\n");
Does the C standard mandate this to always evaluate true?
Yes, according to 6.7.2.1, "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."
Can't find it in the C Standard, but the answer is "yes" - the C++ Standard says:
A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment. ]
As C and C++ POD objects must be compatible, the same must be true for C.
Yes.
There must not be any padding in front of the first member.
The address of a structure is the same as the address of its first member, provided that the appropriate cast is used.
resource
精彩评论