linux offsetof在使用者態C語言實現及樣本

來源:互聯網
上載者:User

若需轉載,請註明出處


linux系統提供的offsetof方法是得到一個結構體中的一個成員欄位的此結構體中的位移位元組,現在使用者態進行實現。


在使用者態進行實現的例子:得到一個結構體中的子結構體中的某一個欄位的值

                         假設前題:只知道大結構的類型、子結構體的名字、子結體的某一欄位的名字                                  

                                思路:先得到子結體中的欄位相對於大結構體的位移量,然後再得到此欄位的地址值,然後再得到此欄位的類型,由此類型把得到的地址值進行強制轉換後就可以得到此欄位的值了,代碼實現:


#include <stdio.h>

#include <stdlib.h>

//子結構體

typedef struct student{

  int age;
  int length;
  char c;
  long width;
  char mm[4];
  int nn;
}ST_STUDENT;

//大結構體

typedef struct school
{
  int schNo;
  ST_STUDENT first;
  int sumpeple;
}ST_SCHOOL;

//樣本為求得子結構體中的char c的值

int main()

{
    int offset, ret, nowadd;
    char *ch = malloc(sizeof(ST_SCHOOL));
    strcpy(ch, "yygydjkthh");
    printf("ch addr is 0x%x char str is %s\n", ch, ch);
    ST_SCHOOL sccxzz;
    sccxzz.first.c = 'a';
    offset = (char *)(&(((ST_SCHOOL *)ch)->first.c)) - ch;
    nowadd = (char *)((char *)&sccxzz + offset);
    typeof(sccxzz.first.c) m = *((typeof(sccxzz.first.c) *)nowadd);
    printf("offset is %d m is %c m len is %d\n", offset, m, sizeof(m));
    printf("ch str is %s\n", ch);
    free(ch);
    exit(0);
}

其中:

//下行得到char c欄位相對於大結構體的位移量

offset = (char *)(&(((ST_SCHOOL *)ch)->first.c)) - ch;

//下行為得到char c的地址

nowadd = (char *)((char *)&sccxzz + offset);

//下行為得到求得的char c地址的值並儲存到以char c欄位型別宣告的一個變數中

//其中typeof為得到某一變數的類型,下行也即為: char m = *((char *)nowadd);

typeof(sccxzz.first.c) m = *((typeof(sccxzz.first.c) *)nowadd);

運行結果為:

ch addr is 0x9191008 char str is yygydjkthh
first.c is a
sccxzz add is 0xbfda205c nowadd is 0xbfda2068 first.c add is 0xbfda2068
offset is 12 m is a m len is 1
ch str is yygydjkthh

聯繫我們

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