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

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