用一个宏求结构体某个变量的相对偏移量

来源:互联网 发布:js监听软键盘弹出收起 编辑:程序博客网 时间:2024/05/22 13:13

 

用一个宏求结构体某个变量的相对偏移量

如:

stuct student

 {

 int a;

 char b[20];

 double ccc;

 }

则:

FIND(student,a); //等于0

FIND(student,b;//等于4

#defineFIND( struc, e ) (size_t)&(((struc*)0)- >e)

 (struc*)0 //表示将常量0强制转化为struc *型指针所指向的地址,当然也可以x,只是到最后还要减去这个x的值

((struc*)0)->e表示在0地址处的结构体struc的成员e 

 &(((struc*)0)- >e)//表示取结构体指针(struc*)0的成员e的地址,因为该结构体的首地址为0,所以其实就是得到了成员e距离结构体首地址的偏移量.

(size_t)//是一种数据类型,为了便于不同系统之间移植而定义的一种无符号型数据,一般为unsigned int

 //扩展一下,现在知道这个变量的地址,求结构体的首地址

#include <stdio.h>

#define FIND(struct,pt,e )((int)pt-(int)(&(((struct*)0)->e)))

struct student

{

int a;

int b;

char c[30];

int d;

};

 

int main()

{

 struct student std;

 int*m = &std.b;

 printf("%d\n",FIND(student,m,b));

 printf("%d\n",&std.a);

}

 

 

 
 

 

原创粉丝点击