Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the C standard say about pointers to structs and their first member?

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?

like image 312
James Morris Avatar asked Jun 13 '10 08:06

James Morris


1 Answers

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

like image 108
Andrey Avatar answered Oct 12 '22 21:10

Andrey