Does the endianness affect how structure members a

2020-07-14 05:32发布

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?

标签: c
5条回答
虎瘦雄心在
2楼-- · 2020-07-14 06:14

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.

查看更多
看我几分像从前
3楼-- · 2020-07-14 06:18

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

查看更多
看我几分像从前
4楼-- · 2020-07-14 06:21

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.

查看更多
Emotional °昔
5楼-- · 2020-07-14 06:22

Endianness doesn't affect the order of the members.

From N1570 6.7.2.1 Structure and union specifiers:

  1. As discussed in 6.2.5, a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence, and a union is a type consisting of a sequence of members whose storage overlap.

There might be padding bytes in between the members and at the end of structure though.

查看更多
家丑人穷心不美
6楼-- · 2020-07-14 06:24

Endianness refers to the order of bytes within the processor's natural types: integers and floats. The top element in a struct 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.

查看更多
登录 后发表回答