C语言宏offsetof

栏目: C · 发布时间: 5年前

内容简介:运行结果如下:示例代码二:执行结果:

C 库宏 offsetof(type, member-designator) 会生成一个类型为 size_t 的整型常量,它是一个结构成员相对于结构开头的字节偏移量。成员是由 member-designator 给定的,结构的名称是在 type 中给定的。

在阅读Linux/UNIX系统编程手册一书时阅读源代码时有如下相关注释:
/* REQ_MSG_SIZE computes size of 'mtext' part of 'requestMsg' structure.
   We use offsetof() to handle the possibility that there are padding
   bytes between the 'clientId' and 'pathname' fields. */

使用offsetof()避免结构成员之间存在填充字节padding bytes,示例代码如下:

示例代码一:
#include <stddef.h>
#include <stdio.h>

struct address {
   char name;
   int phone;
   char street;
};
   
int main()
{
   printf("address 结构中的 name 偏移 = %ld 字节\n",
   offsetof(struct address, name));
   
   printf("address 结构中的 phone 偏移 = %ld 字节\n",
   offsetof(struct address, phone));
   
   printf("address 结构中的 street 偏移 = %ld 字节\n",
   offsetof(struct address, street));
   
   return(0);
}

运行结果如下:

root@52coder:~/workspace# gcc -g -o offset offset.c
root@52coder:~/workspace# ./offset
address 结构中的 name 偏移 = 0 字节
address 结构中的 phone 偏移 = 4 字节
address 结构中的 street 偏移 = 8 字节

示例代码二:

#include <stddef.h>
#include <stdio.h>

struct address {
   char name;
   char street;
   int phone;
};
   
int main()
{
   printf("address 结构中的 name 偏移 = %ld 字节\n",
   offsetof(struct address, name));
   
   printf("address 结构中的 street 偏移 = %ld 字节\n",
   offsetof(struct address, street));
   
   printf("address 结构中的 phone 偏移 = %ld 字节\n",
   offsetof(struct address, phone));

   return(0);
}

执行结果:

root@52coder:~/workspace# ./offset 
address 结构中的 name 偏移 = 0 字节
address 结构中的 street 偏移 = 1 字节
address 结构中的 phone 偏移 = 4 字节

以上所述就是小编给大家介绍的《C语言宏offsetof》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

淘宝、天猫电商运营百科全书

淘宝、天猫电商运营百科全书

刘涛 / 电子工业出版社 / 2016-7 / 59.00元

有人说淘宝、天猫上90%的卖家不赚钱,我认为说得有点大了。因为如果说大家都不赚钱或者在亏钱,为什么去年在做店铺的卖家,今年还在继续?那些不赚钱的卖家,多数是没意识到市场的变化,还在用原来的套路运营店铺。市场在变,但卖家的思路却没有转变,不赚钱也在情理之中,因为淘宝、天猫的玩法变了。做店铺就是好比一场“打怪”升级的游戏,每次的升级都需要强大的装备与攻略。优胜劣汰,能活下去并且能赚钱的卖家,都是在不停......一起来看看 《淘宝、天猫电商运营百科全书》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码