结构和整数的记忆顺序

oyv*_*ind 2 c memory struct unions

我想用struct和uint64_t建立联合,所以我可以用结构引用单个uint16_ts,并将它们连接在uint64_t中.我做了这个测试程序:

#include "stdio.h"
#include "stdint.h"
struct test_struct{
    uint16_t stuff;
    uint16_t a;
    uint16_t b;
    uint16_t c;
};

union test_union{
    struct test_struct str;
    uint64_t uint;
};    

int main(){
    struct test_struct x = {
        .stuff = 0x0000,
        .a = 0x1234,
        .b = 0x5678,
        .c = 0x9ABC
    };
    union test_union y;
    y.str = x;

    printf("y.uint: %llX\n", y.uint);
}
Run Code Online (Sandbox Code Playgroud)

输出变为:

y.uint: 9ABC567812340000
Run Code Online (Sandbox Code Playgroud)

这对我来说是违反直觉的(它应该是0000123456789ABC,或123456789ABC).有人可以向我解释为什么结构中的元素似乎被逆转了吗?

编辑:为了将来参考:字节顺序答案让我困惑,因为,uint16_ts以正确的顺序打印.但这当然是因为他们自己存储的是小端.

Gra*_*and 7

您处于小端平台上,首先存储的字节(具有最低地址)最终位于组合的最低有效位(打印时右侧)uint64_t.

如果您在big-endian平台上运行相同的代码,您将获得预期的结果.您的代码不能在具有不同字节序的系统之间移植.