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

感谢您的支持!!!!

相关推荐
浅念-3 小时前
Linux 开发环境与工具链
linux·运维·服务器·数据结构·c++·经验分享
旺仔.2913 小时前
容器适配器:stack栈 、queue队列、priority queue优先级队列、bitset位图 详解
c++
潜创微科技--高清音视频芯片方案开发4 小时前
2026年C转DP芯片方案深度分析:从适配场景到成本性能的优选指南
c语言·开发语言
刘景贤5 小时前
C/C++开发环境
开发语言·c++
青桔柠薯片6 小时前
从C语言到裸机运行:i.MX6ULL 的 GPIO 控制与编译链接过程分析
c语言·开发语言·imx6ull
OasisPioneer6 小时前
现代 C++ 全栈教程 - Modern-CPP-Full-Stack-Tutorial
开发语言·c++·开源·github
xiaobobo33306 小时前
c语言结构体相关箭头运算符和点号运算符的联系以及c语言的“索引”思想
c语言·箭头运算符·点号运算符·索引思想
liulilittle6 小时前
XDP to TC : TUN eBPF NAT
c++
花开莫与流年错_6 小时前
ZeroMQ基本示例使用
c++·消息队列·mq·示例·zeromq
weixin_537590456 小时前
《C程序设计语言》练习答案(练习1-13)
c语言·开发语言·c#