结构体内存对齐

对齐规则

  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 @ 2022-11-28 21:51  逆行旅者  阅读(56)  评论(0)    收藏  举报