struct字節對齊問題

struct字節對齊問題

代碼驗證

#include <iostream>
#include <stdio.h>
using namespace std;
/*

https://www.cnblogs.com/ningvsban/p/3940153.html
https://blog.csdn.net/m0_37829435/article/details/81348532

總結:
內存對齊原則
1、  對於結構的各個成員,第一個成員位於偏移爲0的位置,以後每個數\
據成員的偏移量必須是min(#pragma pack()指定的數,這個數據成員的自身長度) 的倍數。
2、  在數據成員完成各自對齊之後,結構(或聯合)本身也要進行對齊,對\
齊將按照#pragma pack指定的數值和結構(或聯合)最大數據成員長度中,比較小的那個進行。

*/
#pragma pack(8)
struct A {
	short b;//2+補齊2,保證int c起始地址的偏移量是min(pack(8),int(4))=4的倍數
	int c;//4
	char a;//
};
#pragma pack()

#pragma pack(2)
struct B {
	short b;//2
	int c;//4
	char a;//1+補齊1
};
#pragma pack()

struct C {
	char arr[7];//7+補1
	short b;//2+補2
	int c;//4
	char a;//1+補齊3
};

typedef struct _parent
{
	short c;//2
	char b;//1+補1
	int a;//4
	
}parent;

struct _child
{
	char d;//1+補3,補齊3是爲了保證嵌套類p的偏移起始地址(0)\
		   是嵌套類中最大成員(int)或者實際對齊單位(還是取兩者小的那個)的整數倍,\
		   切記,並不是子類起始變量類型short的整數倍
	parent p;//8
	int e;//4
};


typedef struct _parent1
{
	short c;//2
	char b;//1+補5
	double a;//8

}parent1;

struct _child1
{
	int d;//4+補4,補齊4是爲了保證嵌套類p的偏移起始地址(0)\
		   是嵌套類中最大成員(double)或者實際對齊單位(還是取兩者小的那個)的整數倍
	parent1 p;//16
	char e;//1+補多少?是補3保證當前_child1中的int對齊?還是補7保證與子類中double對齊?,答案是補7
};
int main()
{
	printf("size of struct A = %d \n", sizeof(struct A));//
	//size of struct A = 12,結構體本身按照min(pack(8),int(4))中的最小的int(4)對齊

	printf("size of struct B = %d \n", sizeof(struct B));//
	//size of struct B = 8,結構體本身按照min(pack(2),int(4))中的最小的pack(2)對齊

	printf("size of struct C = %d \n", sizeof(struct C));//
	//size of struct C = 20,結構體按照最大的成員類型int(4)補齊,不是sizeof(arr)大小7

	printf("size of struct _parent = %d \n", sizeof(_parent));//
	//size of struct _parent = 8

	printf("size of struct _child = %d \n", sizeof(struct _child));//

	printf("size of struct _parent1 = %d \n", sizeof(_parent1));//
	//size of struct _parent = 16

	printf("size of struct _child1 = %d \n", sizeof(struct _child1));//

	system("pause");
	return 0;
}

輸出結果

在這裏插入圖片描述

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