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;
}

感谢您的支持!!!!

相关推荐
肆忆_20 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
祈安_3 天前
C语言内存函数
c语言·后端
端平入洛4 天前
auto有时不auto
c++
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost