cpu传输数据大小由它的总线条数决定,32位传输4个字节,64位传输8个字节,在结构体成员占用内存大小不是4和8的倍数时进行补齐。
struct 的内存对齐原则
原则1:前面的地址必须是后面的地址整数倍,不是就补齐
原则2:整个Struct的地址必须是最大字节的整数倍
下面举个例子来说明:
#include<stdio.h>
#include<iostream>
struct student {
int no;
char name[20];
char sex;
};
int main() {
struct student stu1[2] = { { 2020222,"liming",'m'},
{2020222,"li",'a'}
};
printf(" % s\n", stu1[1].name);
printf("%u %u\n", &stu1[0].name, &stu1[1].name);
printf("%d\n",sizeof(stu1[1].no));
printf("%d\n", sizeof(stu1[1].name));
printf("%d\n", sizeof(stu1[1].sex));
printf("%d\n", sizeof(student));
system("pause");
return 0;
}
在对结构体中的成员进行内存计算时,可以发现int类型的成员占用了4个字节,char数组占用了20个字节,char占用了一个字节,但是整个结构体占用的并不是4+20+1=25个字节,而是28个字节。char数组的20个字节可被int的4字节整除,不需要补齐,char要进行补齐到4位,所以是4+20+4=28个字节。