[Solved] What determines the distance between two structure members?


The reason this outputs 4 has to do with the size of each type and struct padding and alignment.

On my system, sizeof(unsigned int) is 4, sizeof(long int) is 8, and sizeof(struct test) is 24. So to ensure that the 64-bit field lies on a 64-bit boundary, the structure is physically laid out like this:

struct test
{
    unsigned int x;     // 4 bytes
                        // 4 bytes padding
    long int y;         // 8 bytes
    unsigned int z;     // 4 bytes
                        // 4 bytes padding
};

So when you take the difference between the offset of x and the offset of z, there are 16 bytes difference. And since we’re doing pointer subtraction, the value of the difference is {byte offset difference} / {element size}. So we have 16 (byte difference) / 4 (sizeof(unsigned int)) == 4.

If sizeof(long int) was 4, then the struct would probably be laid out like this:

struct test
{
    unsigned int x;     // 4 bytes
    long int y;         // 4 bytes
    unsigned int z;     // 4 bytes
};

In which case the output would be 2.

Note that while the ordering of struct members is defined to be sequential, the layout of the padding is is implementation defined. Compilers are free to pad as they see fit.

From section 6.7.2.1 of the C standard:

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.

15 There may be unnamed padding at the end of a structure or union.

solved What determines the distance between two structure members?