结构体大小

发布时间 2023-03-25 21:18:43作者: weixicai

空的结构体,在c中sizeof获取的值是0 (gcc/clang), c++中则是1 (clang++).  《C语言深度解剖》

enum 型变量在编译器会被替换为具体的值,所以sizeof只返回单个变量的值。//不存在遍历enum的循环

编译器在结构体中填充空白是为了随机访问,尽可能提高访问效率。将试着把对每个成员的访问都想象成数组的随机访问。

 

 1 /*
 2  * 编译器在结构体中填充空白是为了随机访问
 3  */
 4 #include <stdio.h>
 5 #include <sys/cdefs.h>
 6 
 7 struct fox {
 8     double z;
 9     int x;
10     short y;
11 } afox;
12 
13 int main(int argc, char *argv[]) {
14     int offset[3] = {0,0,0}; //也可以直接保存各成员的初始地址
15     int max_sizeof = 8;        // sizeof(double)
16 
17     /* 编译器放置结构体的过程
18      * offset = 0
19      */
20 
21     /* 在第一个成员看来,自己是double型数组的第0项,占据0..7比特
22      * 地址为(double *)(&afox)+0 
23      * off =sizeof(double)*0 可占用的起始比特:8
24      */
25     offset[1] = 0;
26 
27     /*在第二个成员看来,自己是int型数组的第1项,占据8..12比特
28      * 起始地址 
29      * (int *)(&afox)+1 < off  4..7<8, 已占用
30      * (int *)(&afox)+2 >= off  8..12>=8, 可以占用
31      * 所以他是第2项
32      * off = sizeof(int)*2 可占用的起始比特:12
33      */
34     offset[1] = 2;
35 
36     /*在第三个成员看来,自己是short int型数组的第2项,占据12..13比特
37      * 起始地址为
38      * (short int *)(&afox)+2 < off    4..5 <12  
39      * (short int *)(&afox)+3 < off    6..7 <12
40      * (short int *)(&afox)+4 < off    8..9 <12
41      * (short int *)(&afox)+5 < off   10..11<12
42      * (short int *)(&afox)+6 >= off   12..13>=12
43      * 所以他是第6项
44      * offset = sizeof(short int)*(6+1) = 14是max_sizeof的倍数吗?
45      * 不是,整个结构体的大小是(14/8+1)*8=16.
46      */
47     offset[2] = 6;
48 
49     /*编译器访问结构体的过程*/
50     /* afox.x */
51     int *pi = (int *) (&afox) + offset[0]; /* 内容为 *pi */
52 
53     /* afox.z */
54     double *pd = (double *) (&afox) + offset[1]; /* 内容为 *pd */
55 
56     /* afox.y */
57     short int *ps = (short int *) (&afox) + offset[2]; /* 内容为 *ps */
58 
59     return 0;
60 }