当前位置:网站首页>自定义实现offsetof

自定义实现offsetof

2022-06-11 21:36:00 爱学代码的学生

什么是offsetof?

offsetof,程序语言,该宏用于求结构体中一个成员在该结构体中的偏移量。

头文件:stddef.h

宏形式:

 size_t offsetof( structName, memberName )

说明:
1. 第一个参数是结构体的名字,第二个参数是结构体成员的名字。

2. 该宏返回结构体structName中成员memberName的偏移量。偏移量是size_t类型的。

代码实现如下:

typedef struct S
{
	char a;
	char c;
	int b;
}S;
#define OFFSETOF(type,name) ((int)&(((type*)0)->name))
int main()
{
	printf("%d\n", OFFSETOF(S, a));
	printf("%d\n", OFFSETOF(S, c));
	printf("%d\n", OFFSETOF(S, b));
	return 0;
}

原网站

版权声明
本文为[爱学代码的学生]所创,转载请带上原文链接,感谢
https://blog.csdn.net/rinki123456/article/details/122680439