首页 > 其他 > 详细

计算结构体中成员变量的偏移

时间:2014-10-15 17:30:32      阅读:244      评论:0      收藏:0      [点我收藏+]

被人问到这个问题,各种解决。

google一下,MFC中有一个OFFSET宏,就有这个功能。

 

写一下:

#define offsetof(structure, member) ((int)(&((structure *)0)->member))

 

eg:

#include <iostream>
using namespace std;
#include <stdio.h>
#define offsetof(structure, member) ((int)(&((structure *)0)->member))

struct test_struct
{
	int a;
	char b;
	int aa[10];
	char bb[2];
};

int main()
{
	cout<<offsetof(struct test_struct, a)<<endl;
	cout<<offsetof(struct test_struct, b)<<endl;
	cout<<offsetof(struct test_struct, aa)<<endl;
	cout<<offsetof(struct test_struct, bb)<<endl;
	return 0;
}

  

计算结构体中成员变量的偏移

原文:http://www.cnblogs.com/2012harry/p/4026606.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!