[导入]求结构体的字段的偏移量

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

posted on 2010-04-27 23:48 janqii 阅读(280) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿

随笔档案(15)

搜索

最新评论

阅读排行榜

评论排行榜