offsetof宏分析
来源:互联网 发布:淘宝助理发布二手宝贝 编辑:程序博客网 时间:2024/05/18 22:40
offsetof宏定义:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)
对这个宏的讲解我们大致可以分为以下4步进行讲解:
1>( (TYPE *)0 ) 0地址强制 "转换" 为 TYPE结构类型的指针;
2>((TYPE *)0)->MEMBER 访问TYPE结构中的MEMBER数据成员;
3>&( ( (TYPE *)0 )->MEMBER) 取出TYPE结构中的数据成员MEMBER的地址;
4>(size_t)(&(((TYPE*)0)->MEMBER)) 结果转换为size_t类型。
offsetof的巧妙之处在于将0地址强制转换为TYPE结构类型的指针,TYPE结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址。可能有的读者会想是不是非要用0呢?当然不是,我们仅仅是为了计算的简便。也可以使用是他的值,只是算出来的结果还要再减去该数值才是偏移地址。来看看如下的代码:
#include<stdio.h>#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)4)->MEMBER)struct test_struct {int num;char ch;float f1;};int main(void){printf("offsetof (struct test_struct,num)=%d\n",offsetof(struct test_struct,num)-4);printf("offsetof (struct test_struct,ch)=%d\n",offsetof(struct test_struct,ch)-4);printf("offsetof (struct test_struct,f1)=%d\n",offsetof(struct test_struct,f1)-4);return 0;}运行结果为:
offsetof (struct test_struct,num)=0offsetof (struct test_struct,ch)=4offsetof (struct test_struct,f1)=8为了让大家加深印象,我们在代码中没有使用0,而是使用的4,所以在最终计算出的结果部分减去了一个4才是偏移地址,当然实际使用中我们都是用的是0。
0 0
- offsetof宏分析
- offsetof宏定义分析
- container_of 宏、offsetof 宏 分析
- offsetof宏
- offsetof宏
- 内核:offsetof + container_of 分析
- Linux内核 container_of 宏和 offsetof 宏分析
- Linux内核 container_of 宏和 offsetof 宏分析
- Linux内核 container_of 宏和 offsetof 宏分析
- Linux内核 container_of 宏和 offsetof 宏分析
- Linux内核 container_of 宏和 offsetof 宏分析
- offsetof宏学习反思
- offsetof宏的使用
- offsetof 宏的简介
- offsetof宏解析
- offsetof宏的用法
- offsetof宏解析
- offsetof与container_of宏
- 欢迎使用CSDN-markdown编辑器
- 网络通信之UIP在STM32上的移植
- 第6章 linux的文件权限与目录配置
- Ubuntu Kylin 16.04 UKUI预览版更换为163软件源
- 我所理解的快速傅里叶变换(FFT)
- offsetof宏分析
- matlab基础知识(2)
- UVA 1388 Graveyard
- 不通过中间变量交换两个变量的值
- Linux应用编程之静态链接库和动态链接库
- 第八周 oj 1992 分数序列
- Error:Failed to find: com.android.support:appcompat-v7:14.+
- HTML5 浏览器支持
- 《从你的全世界路过》之稻城