c\c++ 结构体和共用体的sizeof

  • 结构体变量的sizeof(牵扯到字节对齐机制)
    1. 结构体变量的首地址能够被其最大宽度基本类型成员的大小所整除。
    2. 结构体每个成员相对于结构体首地址偏移量都是成员大小的整数倍,如果有需要,编译器会在成员之间加上填充字节。
    3. 结构体的总大小为结构体最宽基本类型成员的整数倍。

eg;

 1 /*
 2 1.结构体的sizeof
 3 
 4 struct str{
 5     char c1;//char 的偏移量必须是1的倍数
 6     short s1;//short的偏移量必须是2的倍数
 7     int i1; //int型必须是4的倍数
 8 };
 9 那么:sizeof(str)?=1+2+4=7???
10 */
11 #include<iostream>
12 using namespace std;
13 int main() {
14     struct str {
15         char c1;//char 的偏移量必须是1的倍数
16         short s1;//short的偏移量必须是2的倍数
17         int i1; //int型必须是4的倍数
18     };
19     cout << "struct的sizeof:" << sizeof(str);
20 }

 

 结合第二条,所以会在c1和s1之间填充一个字节,最后大小为8个字节

若将c1放在最后

 1 #include<iostream>
 2 using namespace std;
 3 int main() {
 4     struct str {
 5         short s1;//short的偏移量必须是2的倍数
 6         int i1; //int型必须是4的倍数
 7         char c1;//char 的偏移量必须是1的倍数
 8     };
 9     cout << "struct的sizeof:" << sizeof(str);
10 }

 

 结合第二条,编译器会在s1和i1之间添加俩个字节,再结合第三条会在c1后面添加三个字节大小,返回值为12个字节。

  • 公用体变量的sizeof(牵扯到字节对齐机制)
    • 结构体的总大小为结构体最宽基本类型成员的整数倍。

eg:

 

1 #include<iostream>
2 using namespace std;
3 int main() {
4     union un {
5         double x;
6         char y;
7     };
8     cout << "union的sizeof:" << sizeof(un);
9 }

 

 

 

 

 

 若有数组的存在:

#include<iostream>
using namespace std;
int main() {
    union un {
        double x;
        char y[13];
    };
    cout << "union的sizeof:" << sizeof(un);
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-06-20 15:39  每天都要吃早饭  阅读(401)  评论(0编辑  收藏  举报