c語言面試題目之offset函數(shù)的作用

看Linux內(nèi)核的代碼,看到很多地方對(duì)結(jié)構(gòu)體成員求偏移量。相信很多做過嵌入式的同學(xué)在面試中應(yīng)該會(huì)被問到這個(gè)問題。怎么求結(jié)構(gòu)體里面的變量的偏移量??下面我們就解析一下。

#define list_offsetof(type, name) \
(uint64_t)(&(((type*)0)->name))

這個(gè)東西理解起來比較簡(jiǎn)單,也就是定義了一個(gè)type指針,然后取成員變量name的相對(duì)地址。

#include<stdio.h>
typedef struct Test{
  char a;
  int b;
  int c;
}Test_r;
int main(){
    int offsetValue = 0;    
    offsetValue = (int)(&(((Test_r*)0)->b));
    printf("%d",offsetValue); //結(jié)構(gòu)體對(duì)齊,所以輸出4
}

對(duì)于這個(gè)東西的作用是什么那,或者說什么時(shí)候要用到這個(gè)那??下面寫個(gè)小的例子,一個(gè)雙向鏈表操作:

#include<stdio.h>
#define LIST_NODE_INIT(ptr) do{\
    (ptr)->prev = (ptr);\
    (ptr)->next = (ptr);\
}while(0)

#define list_offsetof(type, name) \
    (int)(&(((type*)0)->name))

#define LIST_GET_ENTRY(ptr, type, name) \
    (type*)((int*)(ptr) - list_offsetof(type, name))

//鏈表定義 
typedef struct _list_node {
    struct _list_node *prev;
    struct _list_node *next;
}list_node_t;

//response內(nèi)容 
typedef struct response_content{
    int key;
    int value;
}response_content_t;

//response數(shù)據(jù)結(jié)構(gòu)體 
typedef struct reponse_data{
    response_content_t response_content;
    list_node_t response_node_pool;
}response_data_t;

//定義鏈表頭 
typedef struct response_list{
    int node_count;
    list_node_t response_node_pool;
}response_list;

void list_insert__r(list_node_t *prev, list_node_t *next, list_node_t *ptr)
{
    next->prev = ptr;
    ptr->next = next;
    ptr->prev = prev;
    prev->next = ptr;
}

void list_add_tail__r(list_node_t *head, list_node_t *ptr)
{
    list_insert__r(head->prev, head, ptr);
}

int main(){
    response_list head;
    response_data_t *data;
    response_data_t *tmp_data;
    response_content_t *dataptr = NULL;
    int i =0;
    memset(&head,0,sizeof(response_list));
    LIST_NODE_INIT(&head.response_node_pool);
    data = (response_data_t*)calloc(1,3 * sizeof(response_data_t));
    for(i =0; i < 3;i++){
        tmp_data = (response_data_t*)(data + 1);
        LIST_NODE_INIT(&(tmp_data->response_node_pool));
        list_add_tail__r(&(head.response_node_pool),&(tmp_data->response_node_pool));
    }
    //關(guān)鍵就是我們不需要知道結(jié)構(gòu)體里面的具體內(nèi)容,只要求出偏移地址既可以得到data的地址 
    dataptr = LIST_GET_ENTRY(head.response_node_pool.next,response_data_t,response_node_pool);
    dataptr->key = 1;
    dataptr->value = 2;
    dataptr = LIST_GET_ENTRY(head.response_node_pool.next,response_data_t,response_node_pool);
    printf("%d %d",dataptr->key,dataptr->value);
    
}

對(duì)于結(jié)構(gòu)體我們很多時(shí)候不需要關(guān)注里面的數(shù)據(jù)類型,只想得到自己想要的東西。所以我們就可以統(tǒng)一化通過偏移地址。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容