自動字節對齊
不想要字節對齊的時候,有沒有辦法取消字節對齊?答案是可以,就是在結構體聲明當中,加上__attribute__ ((__packed__))關鍵字,它可以做到讓我們的結構體,按照緊湊排列的方式,占用內存。來段實際代碼:
#include <stdio.h> #include <iostream> using namespace std; struct test1 { char c; int i; }; struct __attribute__ ((__packed__)) test2 { char c; int i; }; int main() { cout << "size of test1:" << sizeof(struct test1) << endl; cout << "size of test2:" << sizeof(struct test2) << endl; }
運行結果:
size of test1:8 size of test2:5
顯而易見,test1結構體里面沒有加關鍵字,它采用了4字節對齊的方式,即使是一個char變量,也占用了4字節內存,int占用4字節,共占用了8字節內存,這在64位機器當中將會更大。
而test2結構體,再加上關鍵字之后,結構體內的變量采用內存緊湊的方式排列,char類型占用1字節,int占用4字節,總共占用了5個字節的內存。
數據結構的對齊的問題。為了讓我們的數據結構以最優的方式存儲,處理,保證讀寫數據結構都一一對齊,我們往往采用3種方式:
1.手動對齊,將數據按從小到大的順序排列,盡量湊齊。
2.使用#pragma pack (n)來指定數據結構的對齊值。
3.使用 __attribute__ ((packed)) ,讓編譯器取消結構在編譯過程中的優化對齊,按照實際占用字節數進行對齊,這樣子兩邊都需要使用 __attribute__ ((packed))取消優化對齊,就不會出現對齊的錯位現象。
轉載:https://blog.csdn.net/u012308586/article/details/90751116