结构体内存对齐

对齐规则

  1. 结构体各成员变量的内存空间的首地址必须是“对齐系数”和“变量实际长度”中较小者的整数倍

  2. 对结构体来说,在其各个数据都对齐之后,结构体本身也需要对齐,即结构体占用的总大小应该为“对齐系数”和“最大数据长度”中较小值的整数倍

  3. 对齐系数即系统位数。即,gcc下,32位系统为4,64位系统为8;MSVC下,默认为8

    32位 64位
    MSVC 8 8
    gcc 4 8

示例代码

#include <stdio.h>
void test_1()
{
struct st1
{
double x1;
char x2;
int x3;
char x4[2];
};
printf("size of long long is %d\n", sizeof(long long));
printf("size of st1 is %d\n", sizeof(st1));
struct st2
{
double a;
char b;
};
printf("size of st2 is %u\n", sizeof(st2));
struct st3
{
short b;
};
printf("size of st3 is %u\n", sizeof(st3));
}
int main()
{
printf("size of ptr is %u\n", sizeof(void*));
test_1();
return 0;
}

不同编译器下运行结果

x86-64 gcc 12.1 32位

size of ptr is 4
size of long long is 8
size of st1 is 20
size of st2 is 12
size of st3 is 2

x86-64 gcc 12.1 64位

size of ptr is 8
size of long long is 8
size of st1 is 24
size of st2 is 16
size of st3 is 2

x64 msvc v19.33

size of ptr is 8
size of long long is 8
size of st1 is 24
size of st2 is 16
size of st3 is 2

x86 msvc v19.33

size of ptr is 4
size of long long is 8
size of st1 is 24
size of st2 is 16
size of st3 is 2

posted @   逆行旅者  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示