用宏实现offsetof 计算结构体成员偏移量

#include <stdio.h>

struct S
{
    
    
	char c1;
	int i1;
	char c2;
};

#define OFFSETOF(a,b)  (int)&(((a*)0)->b)

int main()
{
    
    
	printf("%d\n", OFFSETOF(struct S, c1));
	printf("%d\n", OFFSETOF(struct S, i1));
	printf("%d\n", OFFSETOF(struct S, c2));

	return 0;
}
  • ( (struct S*) 0 )->c1 将0转换成struct S类型指针 ,再指向该结构体成员。
  • &( ( (struct S*) 0 )->c1 ) 获得结构体成员的地址
  • (int) ( &( ( (struct S*)0 )->c1) ) 再转换成int类型得到其成员的偏移量

猜你喜欢

转载自blog.csdn.net/juggte/article/details/115221715