close

struct data {

char a;

int b;

char c;

double d;

short e;

char f;

}__attribute__ ((packed));



一個 struct 被編譯時內部成員變數的記憶體位址是由編譯器決定的,

像上面這個 struct 的話,所有成員變數的大小總和是:

char(1) + int(4) + char(1) + double(8) +short(2) = 16 bytes



但如果用一般的宣告方式沒加上 pack 語法設定的話,

編譯後整個 struct 的大小為 32 bytes,

所以每個成員變數被的記憶體定址並沒有完全連在一起,有部份空隙存在,

只要把每個成員變數的記憶體位址 print 出來看便一清二楚。



加上了 pack 語法設定再編譯後,

整個 struct 的大小為 16 bytes,就的確是每個成員變數的大小總和,

成員變數的記憶體定址也確實連接在一起沒有多餘的空隙。


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 matis 的頭像
    matis

    Never give up

    matis 發表在 痞客邦 留言(0) 人氣()