Hairi Hairi - 8 months ago 30
C Question

Does the endianness affect how structure members are stored into the memory

uint32_t i;
uint32_t i2;
printf("%p %p", &s.i, &s.i2);

If the example above prints:

0 4

That means that the topmost member into the structure is located at the smaller memory address, and the consequent elements are stored at contiguous addresses in increasing order.

What if the platform endianness is inverted? Would that pattern change?
Is this mentioned somewhere in the specification of some C standard?


Endianness is not a factor in the process of deciding offsets of struct members. The initial member will always be allocated at offset zero; the remaining members will be allocated at higher offsets in the order they appear in the struct declaration.

System-independent way to code your program is as follows:

struct {
    uint32_t i;
    uint32_t i2;
intptr_t p = (intptr_t)&s;
intptr_t pi = (intptr_t)&s.i;
intptr_t pi2 = (intptr_t)&s.i2;
printf("%tu %tu\n", pi-p, pi2-p);

Demo 1. intptr_t lets you treat pointers as if they were integers; %tu format specifier prints ptrdiff_t values as unsigned numbers.

You can also do it like this:

struct S {
    uint32_t i;
    uint32_t i2;
printf("%tu %tu\n", offsetof(struct S, i), offsetof(struct S, i2));

Demo 2.