views:

146

answers:

3

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?

+1  A: 

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

Nyan
+4  A: 

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.

anon
+10  A: 

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."

Andrey
I dislike the wording 'suitably converted'. It gives the impression this relationship could be broken by casts (or lack of).
James Morris
@James: The wording is there simply due to the type differences that must exist between a pointer to a struct and a pointer to the first member of the struct.
Michael Burr