小编jim*_*904的帖子

C中结构的大小与重新排列的变量不同

我试图看看为什么当我移动 struct 变量时 struct 的大小会有所不同,我知道涉及填充,但不清楚它在后台做什么

struct test1 {
    long y;
    int a;
    short int b;
    short int t;
}

sizeof(struct test1) = 16

struct test2 {
    long y;
    short int b;
    int a;
    short int t;
}

sizeof(struct test2) = 24

struct test3 {
    int a;
    long y;
    short int b;
    short int t;
}

sizeof(struct test3) = 24
Run Code Online (Sandbox Code Playgroud)

我知道 test1 的大小是 8 + (4+2+2) 没有填充,但我不明白为什么 test2 不返回相同的结果,8 + (2+4+2) 没有填充。

第三个test3我们看到int需要4bytes + 4 padding,long需要8 bytes,short int需要2bytes + 2bytes + …

c struct padding

4
推荐指数
1
解决办法
164
查看次数

标签 统计

c ×1

padding ×1

struct ×1