【C语言】宏offsetof的模拟实现(计算结构体中某变量相对于首地址的偏移)

首先我们应该特别留意 : offsetof 是一个宏,并非是一个函数 !
宏offsetof的介绍:
在这里插入图片描述
参数:第一个是结构体类型名称,第二个是结构体成员名
返回类型:size_t无符号整形

引用的头文件:<stddef.h>

offsetof的使用举列 :

#include <stddef.h>
struct Stu // 注释为相对于起始位置的偏移量
{
	int a;//0~3
	char c;//4
	//5~7
	double d;//8~15
};
int main()
{
	printf("%d\n", sizeof(struct Stu));
	printf("%d\n", offsetof(struct Stu, a));
	printf("%d\n", offsetof(struct Stu, c));
	printf("%d\n", offsetof(struct Stu, d));
	return 0;
}

在这里插入图片描述

offsetof的模拟实现 :

#include <stddef.h>
//写一个宏,计算结构体中某变量相对于首地址的偏移,并给出说明
struct Stu
{
	int a;//0~3
	char c;//4
	//5~7
	double d;//8~15
};
 
#define OFFSETOF(struct_type, mem_name)      (int)&(((struct_type*)0)->mem_name)
 
 
int main()
{
	printf("%d\n", OFFSETOF(struct Stu, a));
	printf("%d\n", OFFSETOF(struct Stu, c));
	printf("%d\n", OFFSETOF(struct Stu, d));
	return 0;
}

在这里插入图片描述
实现详解 :
在这里插入图片描述
我们假设结构体起始地址就是0,这样其成员的地址取出来再强制类型转换为int便可以表示结构体中某个成员相对于起始位置的偏移量,这是一种很巧妙的思考方式,即可实现宏 offsetof 的模拟实现。

最近更新

  1. TCP协议是安全的吗?

    2024-06-12 21:36:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-12 21:36:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-12 21:36:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-12 21:36:02       20 阅读

热门阅读

  1. Nginx GeoIP 使用指南-宝塔识别ip屏蔽地区

    2024-06-12 21:36:02       9 阅读
  2. Thinkphp5实现自定义路由和使用方法

    2024-06-12 21:36:02       5 阅读
  3. E. 日期计算

    2024-06-12 21:36:02       5 阅读
  4. 主机加固方案分享

    2024-06-12 21:36:02       7 阅读
  5. docker拉取镜像失败处理

    2024-06-12 21:36:02       5 阅读
  6. 边界值测试中的边界情况数据

    2024-06-12 21:36:02       6 阅读
  7. 记一次网络故障排查could not load plugin “ifcfg-rh“

    2024-06-12 21:36:02       5 阅读