linux内核中求偏移量的宏定义如下
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
------------------------------宏测试小程序---------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
struct test_struct{
char ch;
int it;
int ul;
};
int main()
{
size_t off=-1;
struct test_struct *st,*rt;
st = (struct test_struct *) malloc (sizeof(struct test_struct));
st->ch='a';
st->it=1;
st->ul=1ul;
/* off =(size_t)&(((struct test_struct *)0)->it);*/
off=offsetof(struct test_struct,it);
// rt=(struct test_struct *)((char *)(&st->it)-off);
rt=(struct test_struct *)(((char *)&(st->it)-(char *)off));
printf("%d %d %d",rt->it,off,sizeof(struct test_struct));
return 0;
}
--------------------------------------------------------------------------------------------------------------
由于4字节补齐的原因,sizeof(struct test_struct)=12,而不是等于9
阅读全文
类别:c/c++ 查看评论文章来源:
http://hi.baidu.com/janqii/blog/item/0b79b1b7512d787f8bd4b2b7.html