Is the first field of a C structure always guarant

2020-02-11 19:05发布

问题:

Regarding the C programming language...

Part of the question at C/C++ Structure offset states that "& does not always point at the first byte of the first field of the structure"

But looking over the "ANSI Rationale" at http://www.lysator.liu.se/c/rat/c5.html it states "no hole may occur at the beginning" in section 3.5.2.1 Structure and union specifiers. So I'm not sure if the "Rationale" is definitive but it does seem to contradict that part of that highly visible question.

So, which is it? Is the first field of a C structure always guaranteed to be at offsetof 0?

struct A
{
    int x;
};

struct B
{
    struct A myA;
    int y;
};

B myB;

Is &myB guaranteed to be the same as &(myB.myA) in a portable way?

(More concretely, the libev user-data trick at Libev, How to pass arguments to relevant callbacks and many other places does assume that the first field in the structure is at offsetof 0... is that really portable?)

回答1:

From the C99 standard section 6.7.2.1 bullet point 13:

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.

The answer to your question is therefore yes.