位元組對齊,c語言位元組對齊

來源:互聯網
上載者:User

位元組對齊,c語言位元組對齊
若是在32bit機器上,使用gcc編譯器,得到的sizeof(A)和sizeof(B)分別為多少?
class A
{
    int a;
    short b;
    int c;
    char d;
};
class B
{
    double a;
    short b;
    int c;
    char d;

};

我個人的理解的對齊 要滿足2點
(1) 每個元素的起始位置要能被其大小(位元組數)整除
(2) 總體大小要能被最大的元素大小整除

那麼第一個
int a :[0..3]
short b :[4..5]
int c 起點要能被4整除 所以是[8..11]
char d [12..13]
一共[0..14]是15個byte
總體要設定為最大(int) 4的倍數 所以應該佔16 byte


第二個
double a : [0..7]
short b : [8..9]
int c 起點要能被4整除[12..15]
char d [16,17]


一個 [0..17]是18個byte
總體要設定為最大(double) 8的倍數, 所以應該佔24 byte


例子:

#include  "stdio.h"struct A{int a;    short b;    int c;    char d;}; struct B{    double a;    short b;    int c;    char d;};int main() {      struct A a;struct B b; printf("%d\n",sizeof(a));printf("%d\n",sizeof(b));getchar();    return 0;  }  
結果是:

16

24

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.