文档详情

计算你结构体长度(Calculate the length of your structure).doc

发布:2017-08-02约7.04千字共10页下载文档
文本预览下载声明
计算你结构体长度(Calculate the length of your structure) 计算结构体长度: http: / / / motadou / article / details / 3521399 结构体对齐包括两个方面的内容 1. 结构体总长度 2. 结构体内各数据成员的内存对齐, 即该数据成员相对结构体的起始位置 结构体大小的计算方法和步骤 1. 将结构体内所有数据成员的长度值相加, 记为sum _ a; 2. 将各数据成员为了内存对齐, 按各自对齐模数而填充的字节数累加到和sum _ a上, 记为sum _ b.对齐模数是 # pragma pack指定的数值以及该数据成员自身长度中数值较小者.该数据相对起始位置应该是对齐模式的整数倍. 3. 将和sum _ b向结构体模数对齐, 该模数是 # pragma pac指定的数值和结构体内部最大的基本数据类型成员长度中数值较小者.结构体的长度应该是该模数的整数倍. 结构体大小计算举例 在计算之前, 我们首先需要明确的是各个数据成员的对齐模数, 对齐模数和数据成员本身的长度以及pragma pack编译参数有关, 其值是二者中最小数.如果程序没有明确指出, 就需要知道编译器默认的对齐模数值.下表是windows xp / dev c + + 和linux / gcc中基本数据类型的长度和默认对齐模数 char short int long double long double windows 长度 1 2 4 4 8 12 模数 1 2 4 4 8 4 linux 长度 1 2 4 4 8 12 模数 1 2 4 4 4 4 例子1: my _ struct struct { char a; long double b; }; 此例子windows和linux计算方法一样, 如下: 步骤1: 所有数据成员自身长度和: 1b + 12b (13b, 13b _ a = sum 步骤2: 数据成员a放在相对偏移0处, 之前不需要填充字节; 数据成员b为了内存对齐, 根据 结构体大小的计算方法和步骤 中第二条原则, 其对齐模数是4, 之前需填充3个字节, sum _ b = sum _ a + 3 = 16 b 步骤3: 按照定义, 结构体对齐模数是结构体内部最大数据成员长度和pragma pack中较小者, 前者为12后者为4, 所以结构体对齐模数是 4.sum _ b是4的4倍, 不需再次对齐. 综上3步, 可知结构体的长度是16b, 各数据成员在内存中的分布如图1所示. 例子2: # pragma pack (2) my _ struct struct { char a; long double b; }; # pragma pack () 例子1和例子2不同之处在于例子2中使用了 # pragma pack (2) 编译参数, 它强制指定对齐模数是2. 此例子windows和linux计算方法一样, 如下: 步骤1: 所有数据成员自身长度和: 1b + 12b (13b, 13b _ a = sum 步骤2: 数据成员a放在相对偏移0处, 之前不需要填充字节; 数据成员b为了内存对齐, According to the second calculation methods and steps structure in the size of the principles, the alignment modulus is 2, before filling 1 bytes, sum_b = sum_a + 1 = 14B Step 3: according to the definition of the structure alignment module is inside the structure length and the largest data member pragma Pack is smaller, the former is 12 and 2 for the latter, so the structure alignment modulus is 2. Sum_b is 7 times 2, without re alignment. In the 3 step, the structure length is 14B, the distribution of each data member in the memory as shown in figure 2. Example 3: Struct my_struct { Char a; Double b; Char c; }; The first two cases, data
显示全部
相似文档