字节对齐测试实例
先看理論:
1. 更改C編譯器的缺省字節對齊方式
在缺省情況下,C編譯器為每一個變量或是數據單元按其自然對界條件分配空間。一般地,可以通過下面的方法來改變缺省的對界條件:
· 使用偽指令#pragma pack (n),C編譯器將按照n個字節對齊。
· 使用偽指令#pragma pack (),取消自定義字節對齊方式。
另外,還有如下的一種方式:
· __attribute((aligned (n))),讓所作用的結構成員對齊在n字節自然邊界上。如果結構中有成員的長度大于n,則按照最大成員的長度來對齊。
· __attribute__ ((packed)),取消結構在編譯過程中的優化對齊,按照實際占用字節數進行對齊。
?
測試源碼:
#include <stdio.h> #include <iostream> #include <map>using namespace std;struct stu {char sex;long long ss; // 8short length; // 2int s2; // 4char name[10]; //}__attribute__((aligned(1))); // 按最大成員的長度來對齊(但不超過N,否則按N對齊;N=4(32位機器)/8(64位機器)) }__attribute__((packed)); // 1字節對齊void test() {struct stu my_stu;cout << sizeof(my_stu) << endl;printf("%p, %p, %p, %p, %p\n", &my_stu.sex, &my_stu.ss, &my_stu.length, &my_stu.s2, &my_stu.name); }int main() {test(); return 0; }測試結果與我代碼中的注釋一致,代碼本身也比較簡單,就不解釋了!
總結
- 上一篇: Lowagie 导出html的内容到 p
- 下一篇: redhat配置centos的yum源