当前位置:网站首页>C语言程序设计 | offsetof宏的讲解及其模拟实现
C语言程序设计 | offsetof宏的讲解及其模拟实现
2022-07-27 22:27:00 【回不去_从前了丶】
offsetof宏讲解
首先来看下在cpluscplus对于offsetof宏给出的定义

macro代表的是宏
其中参数有两个
- type代表的是类型
- member代表的成员
该宏的作用是用来求出结构体成员相对于首地址的偏移量。
使用的方法如下,代码实例:
struct S
{
char c1;
int i;
char c2;
};
#include <stdio.h>
#include <stddef.h>
int main()
{
struct S s = {
0};
printf("%d\n", offsetof(struct S, c1));
printf("%d\n", offsetof(struct S, i));
printf("%d\n", offsetof(struct S, c2));
return 0;
}
打印结果:

讲解:

模拟实现offsetof宏
在讲解中,我们可以看出,偏移量就是地址减去首地址的出来的一个数,那么我们假设地址为0,我们只需要取出地址,这个地址就是偏移量。
代码实例:
#include <stddef.h>
#include <stdio.h>
struct S
{
char c1;
int i;
char c2;
};
#define OFFSETOF(type, m_name) (size_t)&(((type*)0)->m_name)
int main()
{
struct S s = {
0};
printf("%d\n", OFFSETOF(struct S, c1));
printf("%d\n", OFFSETOF(struct S, i));
printf("%d\n", OFFSETOF(struct S, c2));
return 0;
}
讲解:
首先我们把地址设为0,那么就有:
#define OFFSETOF(type,m_name) ((type*)0)
这里呢就是地址设置为0,类型为type*类型的,注意这里的type只是进行替换,并不代表实际的类型
取出地址之后呢,我们就去找结构体的成员,那么就有:
#define OFFSETOF(type,m_name) (((type*)0)->m_name)
这里找到结构体的成员之后,我们再取出这个成员的地址,那么就有:
#define OFFSETOF(type,m_name) &(((type*)0)->m_name)
取出地址之后呢,我们再进行类型的强制转换。
#define OFFSETOF(type,m_name) (size_t)(&(((type*)0)->m_name))
打印结果:

边栏推荐
- LSB steganography
- ASML推出第一代HMI多光束检测机:速度提升600%,适用于5nm及更先进工艺
- 激活最大化
- Leetcode - find the median of two positively ordered arrays
- Confused SCM matrix keys
- 网络设备硬核技术内幕 防火墙与安全网关篇 (小结)
- Multithreading and multithreaded programming
- LeetCode - 寻找两个正序数组的中位数
- Can TSMC Samsung build a production line without American equipment for Huawei?
- Network device hard core technology insider firewall and security gateway (VII) virtualization artifact (Part 1)
猜你喜欢
随机推荐
startUMl
Read cmake in one article
推荐系统-模型:dssm双塔模型做embedding的召回
Border width border fillet border color
Network equipment hard core technology insider firewall and security gateway chapter (VI) security double repair under the law
The most detailed summary of common English terms in the chip industry (quick grasp of graphics and text)
福特SUV版“野马”正式下线,安全、舒适一个不落
Data analysis: disassembly method (details)
自用图床搭建教程
深度刨析数据在内存中的存储
Scrollview, tableview nested solutions
Basic operations of MySQL database (2) --- Based on data table
一文读懂CMake
Resolved Unicode decodeerror: 'UTF-8' codec can't decode byte 0xa1 in position 0: invalid start byte
Ddt+yaml implementation of data driven mechanism based on unittest
Basic operations of MySQL database (I) --- Based on Database
推荐系统-指标:ctr、cvr
Firefox 103, the Firefox browser, has been released to improve performance under high refresh rate displays
0-1背包问题
大众中国豪掷80亿,成国轩高科第一大股东









