offset宏的講解

來源:互聯網
上載者:User
1.offset宏講解

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)

對這個宏的講解我們大致可以分為以下4步進行講解:

1>( (TYPE *)0 )  0地址強制 "轉換" 為 TYPE結構類型的指標;

2>((TYPE *)0)->MEMBER   訪問TYPE結構中的MEMBER資料成員;

3>&( ( (TYPE *)0 )->MEMBER)取出TYPE結構中的資料成員MEMBER的地址;

4>(size_t)(&(((TYPE*)0)->MEMBER))結果轉換為size_t類型。

宏offsetof的巧妙之處在於將0地址強制轉換為 TYPE結構類型的指標,TYPE結構以記憶體空間首地址0作為起始地址,則成員地址自然為位移地址。可能有的讀者會想是不是非要用0呢?當然不是,我們僅僅是為了計算的簡便。也可以使用是他的值,只是算出來的結果還要再減去該數值才是位移地址。來看看如下的代碼:

  #include<stdio.h>

  #defineoffsetof(TYPE, MEMBER) ((size_t) &((TYPE *)4)->MEMBER)

   struct test_struct {

           int num;

           char ch;

          float f1;

  };

 int main(void)

  {

     printf("offsetof (struct test_struct,num)=%d\n",offsetof(struct test_struct,num)-4);

     printf("offsetof (structtest_struct,ch) =%d\n",offsetof(struct test_struct,ch)-4);

     printf("offsetof (struct test_struct,f1)=%d\n",offsetof(struct test_struct,f1)-4);

          return 0;

  }

運行結果為:

jibo@jibo-VirtualBox:~/cv_work/work/list/offset $ ./main

offsetof (struct test_struct,num) =0

offsetof (struct test_struct,ch) =4

offsetof (struct test_struct,f1) =8

為了讓大家加深印象,我們在代碼中沒有使用0,而是使用的4,所以在最終計算出的結果部分減去了一個4才是位移地址,當然實際使用中我們都是用的是0。

二.舉例體會offsetof宏的使用:

  #include<stdio.h>

  #defineoffsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

   struct test_struct {

           int num;

           char ch;

          float f1;

  };

 int main(void)

  {

      printf("offsetof(struct test_struct,num) =%d\n",offsetof(struct test_struct,num));

     printf("offsetof (structtest_struct,ch) =%d\n",offsetof(struct test_struct,ch));

     printf("offsetof (struct test_struct,f1)=%d\n",offsetof(struct test_struct,f1));

          return 0;

  }

執行結果為:

jibo@jibo-VirtualBox:~/cv_work/work/list/offset $ ./main

offsetof (struct test_struct,num) =0

offsetof (struct test_struct,ch) =4

offsetof (struct test_struct,f1) =8

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.