首页 > 代码库 > 结构体,共用体,枚举所占内存大小

结构体,共用体,枚举所占内存大小

结构体要注意位补齐(有4位补齐和8位补齐,默认8位)

 1 #include<stdio.h>
 2 #pragma pack(push)
 3 #pragma pack(4)
 4 struct test
 5 {    
 6     
 7     char a; //补3位
 8     long c;
 9     char d;
10     char h;//补2位
11     int b;
12     char e;  //补3位或补7位  
13     double f;
14     char g;   //补3位或补7位
15 }s1;
16 #pragma pack(pop)
17 
18 typedef struct{
19     double a;
20     char b;
21 }s2;
22 
23 union test2
24 {    
25     char a;
26     short b;
27 }s3;
28 
29 enum week{sun=7,mon=1,tue,wed,thu,fri,sta};
30 enum week weekday;
31 
32 void main(void)
33 {
34     printf("s1:%d \n",sizeof(s1));
35     printf("s2:%d \n",sizeof(s2));
36     printf("s3:%d \n",sizeof(s3));
37     printf("week:%d \n",sizeof(weekday));
38 } 

以下是运行结果

技术分享

结构体,共用体,枚举所占内存大小