10

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?

3 Answers 3

12

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

2
  • 1
    I dislike the wording 'suitably converted'. It gives the impression this relationship could be broken by casts (or lack of). Jun 13, 2010 at 9:23
  • @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. Jun 13, 2010 at 16:50
5

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.