为什么在最后一个大小为1个字节的成员之后需要填充

SRI*_*NTH 2 c compilation padding

我已经读过字符是一种特例,在单个机器单词中的任何位置它们都同样昂贵,因此它们没有首选的对齐方式。

根据上述声明两者的尺寸Struct_1Struct_2应为5个字节。在Struct_1正在占用5个字节按期望但Struct_2正在占用8个字节。

请解释一下这背后的原因。

更进一步,我已经在中打印了各个成员的地址Struct_2。它确认在最后一个成员之后添加了填充空间char g

为什么在最后一个成员的末尾需要填充?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Struct_1 {
    char a;
    char b;
    char c;
    char d;
    char e;
} Struct_1;

typedef struct Struct_2 {
    int  f;
    char g;
} Struct_2;

int main(void) {
    Struct_2 strc2;

    printf("\tsizeof(Struct_1): %ld\n", sizeof(Struct_1));
    printf("\tsizeof(Struct_2): %ld\n", sizeof(Struct_2));

    printf("\tsizeof(strc2.f) : %ld\n\n", sizeof(strc2.f));

    printf("\t&(strc2.f) = %p\n", &(strc2.f));
    printf("\t&(strc2.g) = %p\n", &(strc2.g));

    return (0);
}
Run Code Online (Sandbox Code Playgroud)

上面代码的输出:

sizeof(Struct_1): 5 
sizeof(Struct_2): 8 
sizeof(strc2.f) : 4 

&(strc2.f) = 0x7ffe07b08c50 
&(strc2.g) = 0x7ffe07b08c54
Run Code Online (Sandbox Code Playgroud)

Gau*_*gal 5

结构也必须根据最大元素的大小对齐(int此处)。请记住,您可以拥有一个结构数组,因此必须考虑到具有最大尺寸的元素来对齐每个元素。

考虑Struct_2在内存中是连续的。

100 f1
101 f2
102 f3
103 f4
104 g1
105 padding since f has to be aligned at an address divisible by 4
106 padding since f has to be aligned at an address divisible by 4
107 padding since f has to be aligned at an address divisible by 4
108 f1
......
Run Code Online (Sandbox Code Playgroud)