分类: C/C++
2011-04-28 16:55:08
linux内核中求偏移量的宏定义如下
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
------------------------------宏测试小程序---------------------------------------------------------------------
#include
#include
#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