struct
{
uint32_t i;
uint32_t i2;
}s;
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 thestruct
declaration.System-independent way to code your program is as follows:
Demo 1.
intptr_t
lets you treat pointers as if they were integers;%tu
format specifier printsptrdiff_t
values as unsigned numbers.You can also do it like this:
Demo 2.
Endianness refers to the order of the bytes comprising a digital word in computer memory
C
struct
is NOT a digital word (it is not an entity with which CPU deals), so the answer is no, endianness does not affect how structure members are stored into the memoryWhat does affect how structure members are stored into the memory is Data structure alignment, which may add some padding between members to align member address to make it equal to some multiple of the word size
Structure members' layout is implementation dependent, so it can vary between compilers' brands, chosen optimization modes and destination architectures. Generally, though, the endiannes alone is the order of bytes in multi-byte types (like
int32
), so it shouldn't affect the order of multi-byte chunks of data.Endianness doesn't affect the order of the members.
From N1570 6.7.2.1 Structure and union specifiers:
There might be padding bytes in between the members and at the end of structure though.
Endianness refers to the order of bytes within the processor's natural types:
integers
andfloats
. The top element in astruct
will always come first in memory regardless of endianness. You do have to mind out for the gaps as usually structs are padded (byte aligned) dependant on compiler etc.