计算结构体偏移量

方法一、c标准库

C 库宏 offsetof(type, member-designator) 会生成一个类型为 size_t 的整型常量,它是一个结构成员相对于结构开头的字节偏移量。成员是由 member-designator 给定的,结构的名称是在 type 中给定的。

下面是 offsetof() 宏的声明。

offsetof(type, member-designator)

参数

  • type -- 这是一个 class 类型,其中,member-designator 是一个有效的成员指示器。
  • member-designator -- 这是一个 class 类型的成员指示器。

返回值

该宏返回类型为 size_t 的值,表示 type 中成员的偏移量。

实例

下面的实例演示了 offsetof() 宏的用法。

#include 
#include struct address {char name[50];char street[50];int phone;
};int main()
{printf("address 结构中的 name 偏移 = %d 字节。\n",offsetof(struct address, name));printf("address 结构中的 street 偏移 = %d 字节。\n",offsetof(struct address, street));printf("address 结构中的 phone 偏移 = %d 字节。\n",offsetof(struct address, phone));return(0);
} 

让我们编译并运行上面的程序,这将产生以下结果:

address 结构中的 name 偏移 = 0 字节。
address 结构中的 street 偏移 = 50 字节。
address 结构中的 phone 偏移 = 100 字节。

方法二、不使用c标准库,自定义宏函数

typedef struct _st
{int a;char b[64];char c;
}st;st *p=NULL;int off = -1;分别计算各成员偏移量off =(int)&(p->a);printf("off_a=%d\n",off);//0off =(int)&(p->b);printf("off_b=%d\n",off);//4off =(int)&(p->c);printf("off_c=%d\n",off);//68NULL其实就是0,可以将结构体类型st映射到内存地址0,于是p可以直接用0替换,并转换为p所指向的地址空间数据类型,指针必须指定类型off =(int)&(((st*)0)->a);printf("off_a=%d\n",off);//0off =(int)&(((st*)0)->b);printf("off_b=%d\n",off);//4off =(int)&(((st*)0)->c);printf("off_c=%d\n",off);//68

根据上面的推算,可以总结如下宏函数

#define OFFSETOF(TYPEST,MEMBER) ((size_t)&((TYPEST*)0)->MEMBER)

#define OFFSET(TYPEST,MEMBER) ((size_t)&((TYPEST*)0)->MEMBER)参数一 是结构体类型参数二 是需要结算偏移量的成员typedef struct node
{int a;char b[64];double c;
}node;node* p=NULL;node a={1,"abc",8.4};int asizeoffset = OFFSET(node,a);//使用宏计算成员a偏移量int bsizeoffset = OFFSET(node,b);//使用宏计算成员b偏移量int csizeoffset = OFFSET(node,c);//使用宏计算成员c偏移量printf("%d\n",asizeoffset);//0printf("%d\n",bsizeoffset);//4printf("%d\n",csizeoffset);//72printf("a=%p\n",&a);//0xC6FAC0printf("node.a=%p\n",(char*)&a+asizeoffset);//0xC6FAC0printf("node.a=%p\n",&a.a);//0xC6FAC0printf("node.b=%p\n",(char*)&a+bsizeoffset);//0xC6FAC4printf("node.b=%p\n",&a.b);//0xC6FAC4printf("node.c=%p\n",(char*)&a+csizeoffset);//0xC6FB08printf("node.c=%p\n",&a.c);//0xC6FB08根据偏移量取值先将结构体变量起始地址转换成char* 类型,然后加上成员的偏移量,然后整体指针类型换为成员变量的类型即可。printf("node.a=%d\n",*(int*)((char*)&a+asizeoffset));//1printf("node.b=%s\n",*(char (*)[64])((char*)&a+bsizeoffset));//abcprintf("node.c=%f\n",*(double*)((char*)&a+csizeoffset));//8.400000


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部