/*
* offsetof是一个宏定义,可用于求结构体变量中某个成员(member)在整个结构体(类型为type)中的偏移量
*
*/
#include<iostream>
using namespace std;
typedef struct node_s node_t;
struct node_s
{
int a;
int b;
double c;
node_t *d;
};
#define myoffsetof(type, member) (size_t)&(((type *)0)->member)
int main(void)
{
cout<<myoffsetof(node_t, a)<<endl;
cout<<myoffsetof(node_t, b)<<endl;;
cout<<myoffsetof(node_t, c)<<endl;;
cout<<myoffsetof(node_t, d)<<endl;;
//printf("%s\n%s\n%d\n",__func__,__FILE__,__LINE__);
return 1;
}
/*
*输出如下:
*0
*4
*8
*16
*/
offsetof实现方式
最新推荐文章于 2024-01-29 09:03:00 发布
本文介绍了一个用于计算结构体成员偏移量的宏定义offsetof。通过一个具体的结构体node_t示例,展示了如何使用该宏来获取成员变量a、b、c和d在结构体中的偏移位置。
1969

被折叠的 条评论
为什么被折叠?



