offsetof宏计算某变量相对于首地址的偏移量

宏:offsetof的使用

cpp 复制代码
//offsetof (type,member)
//type是结构体的类型名,member是结构体中的成员名。
cpp 复制代码
struct Student
{
	char name[5]; // 姓名
	int age;       // 年龄
	float score;   // 成绩
};

int main()
{
	struct Student s;

	printf("%zd\n", offsetof(struct	Student, name));
	printf("%zd\n", offsetof(struct	Student, age));
	printf("%zd\n", offsetof(struct	Student, score));

	return 0;
}

我们通过画图可以只管看出结构体是如何存储数据的:

可以发现通过offsteof 宏确实可以准确的计算出每个成员的偏移量,这就是offsetof宏的的作用。

offsetof宏的实现

cpp 复制代码
#define my_offsetof(TYPE,MEMBER)      (size_t)&(((TYPE*)0)->MEMBER)

来使用一下:

cpp 复制代码
#define my_offsetof(TYPE,MEMBER)      (size_t)&(((TYPE*)0)->MEMBER)
struct Student
{
	char name[5]; // 姓名
	int age;       // 年龄
	float score;   // 成绩
};
int main()
{
	struct Student s;

	printf("%p\n", &s);
	printf("%p\n", &(s.name));
	printf("%p\n", &(s.age));
	printf("%p\n", &(s.score));


	printf("%zd\n", my_offsetof(struct	Student, name));
	printf("%zd\n", my_offsetof(struct	Student, age));
	printf("%zd\n", my_offsetof(struct	Student, score));
	return 0;
}

感谢您的支持!!!!

相关推荐
卷无止境1 天前
C++ 的Eigen 库全解析
c++
卷无止境1 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴1 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18003 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴3 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨4 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4568 天前
C++进阶(1)——前景提要
c++
夜悊8 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴8 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0019 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp