700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 计算结构体偏移量

计算结构体偏移量

时间:2021-10-14 08:42:15

相关推荐

计算结构体偏移量

方法一、c标准库 <stddef.h>

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 <stddef.h>#include <stdio.h>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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。