标签:
// 对齐 : 结构体中各成员变量要从自身类型所占内存空间长度的倍数开始存储。大于4个字节的按4个字节算
// 对齐也就是: 结构体中前一个类型的变量补的位数要根据它后面的变量类型来判定!
// 补齐 : 在结构体存储空间的尾端要按结构体所占空间最大的成员变量的所占空间长度的倍数来补上。大于4个字节的按4个字节算。
// 补齐也就是: 结构体的最后的长度要根据结构体中最大成员变量的数据类型来判断,前者必须是后者的整数倍
// for example :
1 #include <stdio.h> 2 typedef struct test { 3 char name[18]; 4 int word; 5 char bit; 6 double number; 7 short age; 8 9 } mix; 10 11 int main () { 12 mix hello; 13 int n = sizeof (n); 14 printf("%d \n", n); // 结果是 48 15 return 0; 16 }
As we have expected, the result is 48, well, how could we get it ? Now let us explain it :
分步解析 :
// 1: name[18] -> 18 bytes 0 - 18 ->20
// 2: word -> 4 bytes 20 - 24
// 3: bit -> 1 bytes 24 - 25 ->32
// 4: number -> 8 bytes 32 - 40
// 5: age -> 2 bytes 40 - 42
// 6: 最大字节数是 8(数组是char类型的,字节数为1), 而最后的结构体长度要是最大字节数的整数倍,所以补位到48
标签:
原文地址:http://www.cnblogs.com/renlovej/p/4458347.html