linux 结构体对齐大小计算

1.对齐大小,可以设置,若对齐大于结构体中最大类型变量,则按照结构体中最大类型长度进行对齐;
2.类型变量小于对齐大小,则需要进行补齐

#include <stdio.h>

typedef struct{
	int a;
	double b;
	short c;
}Teacher_def;
// 按照8字节进行对齐
/*
	a a a a * * * *
	b b b b b b b b
	c c * * * * * *
	sizeof(Teacher_def):24
*/

typedef struct{
	double b;
	int a;
	short c;
}Teacher_def1;

// 按照8字节进行对齐
/*
	b b b b b b b b
	a a a a c c  * *
	sizeof(Teacher_def1):16
*/
typedef struct{
	char  a[3];
	int b;
	Teacher_def t;
	double c;
	short d;
}Teacher_def2;
// 按照8字节进行对齐
/*
	a a a b b b b *
	a a a a * * * *
	b b b b b b b b
	c c * * * * * *
	c c c c c c c c
	d d * * * * * *
	sizeof(Teacher_def2):48
*/
int main()
{
	Teacher_def t;
	Teacher_def1 t1;
	Teacher_def1 t2;
	printf("%d\n", sizeof(t));
	printf("%d\n", sizeof(t1));
	printf("%d\n", sizeof(t2));

	return 0;
}

运行结果:
24
16
48
Press any key to continue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章