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?
Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added between struct members, to ensure that the latter one uses the correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.
Little Endian Byte Order: The least significant byte (the "little end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory. In these definitions, the data, a 32-bit pattern, is regarded as a 32-bit unsigned integer.
If my computer reads bytes from left to right, and your computer reads from right to left, we're going to have issues when we need to communicate. Endianness means that the bytes in computer memory are read in a certain order. We won't have any issues if we never need to share information.
Given this explanation, it's clear that endianness doesn't matter with C-style strings. Endianness does matter when you use a type cast that depends on a certain endian being in use.
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;
}s;
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.
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 memory
What 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With