看Linux内核的代码,看到很多地方对结构体成员求偏移量。相信很多做过嵌入式的同学在面试中应该会被问到这个问题。怎么求结构体里面的变量的偏移量??下面我们就解析一下。
#define list_offsetof(type, name) \
(uint64_t)(&(((type*)0)->name))
这个东西理解起来比较简单,也就是定义了一个type指针,然后取成员变量name的相对地址。
#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); //结构体对齐,所以输出4
}
对于这个东西的作用是什么那,或者说什么时候要用到这个那??下面写个小的例子,一个双向链表操作:
#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内容
typedef struct response_content{
int key;
int value;
}response_content_t;
//response数据结构体
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));
}
//关键就是我们不需要知道结构体里面的具体内容,只要求出偏移地址既可以得到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);
}
对于结构体我们很多时候不需要关注里面的数据类型,只想得到自己想要的东西。所以我们就可以统一化通过偏移地址。