1. 程式人生 > >字節對齊-------結構體、共用體

字節對齊-------結構體、共用體

C/C++

字節對齊
結構體字節對齊:(結構體成員的數據類型為基本數據類型(int,double,char,short,long等))
結構體的總大小是結構體成員中最寬基本數據類型大小的整數倍
#include<iostream>
using namespace std;
struct S0
{
int a;
char b;
short c;
};
struct S1
{
char b;
int a;
short c;
};
struct S2
{
short d;
char b;
short e;
int a;
short c;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
S2 s2;
cout << sizeof(s2) << endl;
}
輸出結果:
8
12
16

總結:對於這種成員數據類型都為基本數據類型的結構體:
1.若最寬基本數據類型的成員位置在結構體成員的邊上(最上邊/最下邊),則其它小的數據類型字節數之和與最寬的類型大小對齊(整數倍),而結構體的大小就是最寬的數據類型大小與其它的對其後的大小(整數倍)之和;
如S0:
最寬(大)的類型為int(4字節) 其它:char(1個字節),short(2個字節) 總共3字節,與int對齊後為4字節,則結構體S0的字節大小為4+4=8 字節

2.若最寬基本數據類型的成員在結構體成員的中間位置,則是最寬的成員的上面和下面分別與最寬數據類型對齊(整數倍),則結構體的大小為3者之和(對齊後的)
如S1:
最寬(大)的類型為int(4字節) 上面:char(1字節) 對齊後占用4字節
下面:short(2字節) 對齊後占用4字節 則結構體的大小為4+4+4=12字節
如S2:
最寬(大)的類型為int(4字節) 上面:short(2字節) + char(1字節) +short(2字節)=5字節 對齊後占用8字節 (4的整數倍)
下面:short(2字節) 對齊後占用4字節 則結構體的大小為8+4+4=16字節

共用體大小:共用最寬的數據類型的空間大小


#include<iostream>
using namespace std;
union S1
{
int a;
long long b;
};

union S0
{
short b[3];
int a;
short c;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
}
執行結果:
8
8
分析:
S1;最寬數據類型為long long(8)字節,所以共用這8個字節空間,共用體大小為8字節
S0:最寬數據類型為int(4字節),但是數組b short(2字節)*3=6字節,向上取4整數倍為8,所以共用8個字節空間

共用體裏面包含結構體(或者共用體)
共用體的最大基本數據類型大於或等於其內部結構體(共用體)的在空間大小,則共用最大基本類型的字節空間
#include<iostream>
using namespace std;
struct S0
{
int a;
};
union S1
{
int a;
S0 b;
long long c;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
}
輸出:
4
8

共用體的最大基本數據類型小於其內部結構體(或者共用體)的字節空間,則共用結構體(或者共用體)字節空間
#include<iostream>
using namespace std;
struct S0
{
int a;
long long b;
};

union S1
{
int a;
S0 b;
long c;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
}
輸出:
16
16

結構體裏面包含共用體(或者結構體)
結構體裏面的基本數據類型沒有其內部共用體(或者結構體)中的最大基本數據類型大;則遵照結構體中只有基本數據類型的規則向其內部共用體(結構體)中的最大基本數據類型字節數對齊
#include<iostream>
using namespace std;
union S1
{
int a;
};
struct S0
{
short a;
S1 cl;
char b;
};
void main()
{
S1 s0;
cout << sizeof(s0) << endl;
S0 s1;
cout << sizeof(s1) << endl;
}
輸出:
4
12
#include<iostream>
using namespace std;
struct S0
{
int a;
long long b;
};
struct S1
{
int a;
S0 d;
long b;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
}
輸出:
16
32

結構體裏面的基本數據類型比其內部共用體(或者結構體)中的最大基本數據類型大或者相同,則向結構體裏面的最大數據類型對齊(小的加起來對齊時還需加上共用體的大小)
#include<iostream>
using namespace std;
union S1
{
int a;
};
struct S0
{
int a;
S1 cl;
long long b;
};
void main()
{
S1 s0;
cout << sizeof(s0) << endl;
S0 s1;
cout << sizeof(s1) << endl;
}
輸出:
4
16
#include<iostream>
using namespace std;
struct S0
{
char a;
};
struct S1
{
S0 d;
long b;
};
void main()
{
S0 s0;
cout << sizeof(s0) << endl;
S1 s1;
cout << sizeof(s1) << endl;
}
輸出:
1
8

字節對齊-------結構體、共用體