offsetof宏的原理以及作用
来源:互联网 发布:淘宝网看手机 编辑:程序博客网 时间:2024/06/08 13:49
原理:
虚拟一个TYPE类型的结构体变量,通过TYPE.MEMBER的方式来访问MEMBER成员,进而得到MEMBER成员相对于整个结构体首地址的偏移量。
作用:为接下来的container_of宏的讲解出现做铺垫
offsetof宏: #define offsetof(TYPE,MEMBER) ((int) &((TYPE *)0)->MEMBER)
接下来看看例程就明白了,其实这个宏挺简单的,&((TYPE *)0)->MEMBER其实相当于得到了成员的偏移减去0地址偏移,也就是结构体的首地址,进而就得到了该成员相当于整个结构体的偏移量。
#include <stdio.h>#define offsetof(TYPE,MEMBER) ((int) &((TYPE *)0)->MEMBER)#pragma pack(4)struct ptr{char a ; short b ; int c ; double d ;};#pragma pack()int main(void){struct ptr Pt ;printf("ptr:%d\n",sizeof(struct ptr));//16//相对地址偏移量 int offset = offsetof(struct ptr,a); //0printf("offset:%d\n",offset);int offset1 = offsetof(struct ptr,b); //2printf("offset1:%d\n",offset1);int offset2 = offsetof(struct ptr,c); //4printf("offset2:%d\n",offset2);int offset3 = offsetof(struct ptr,d); //8printf("offset3:%d\n",offset3);return 0 ;}
0 0
- offsetof宏的原理以及作用
- container_of与offsetof的原理
- offsetof宏的使用
- offsetof 宏的简介
- offsetof宏的用法
- offsetof宏实现以及container_of《代码》
- Handler的作用以及工作原理
- stdafx.h的作用以及原理
- stdafx.h的作用以及原理
- stdafx.h的作用以及原理
- offsetof宏
- offsetof宏
- OpenSessionInViewFilter原理以及作用
- apply()原理以及作用
- C语言中offsetof宏的应用
- C语言中offsetof宏的应用
- C语言offsetof宏的说明
- C语言中offsetof宏的应用
- 反射
- 关于烧饼游戏修改器的分析
- 在命令行下运行PHP脚本[带参数]的方法
- 如何处理分类中的训练数据集不均衡问题
- PHP 使用非对称加密算法 (RSA)
- offsetof宏的原理以及作用
- 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建
- jsp9大内置对象详解
- androoid framework学习之 - RILd相关介绍
- int,float,double型转换深析
- SQL语句输出直角三角形
- SAP修改物料价格那些事
- Spring3系列: Spring AOP——Pointcut,Advisor
- 实现一个选择排序程序,排序整型数组