C语言宏offsetof
C 库宏 offsetof(type, member-designator) 会生成一个类型为 size_t 的整型常量,它是一个结构成员相对于结构开头的字节偏移量。成员是由 member-designator 给定的,结构的名称是在 type 中给定的。在阅读Linux/UNIX系统编程手册一书时阅读源代码时有如下相关注释:
/*REQ_MSG_SIZEcomputes sizeof'mtext'partof'requestMsg'structure.Weuse offsetof()tohandle the possibility that there are paddingbytesbetween the'clientId'and'pathname'fields. */
使用offsetof()避免结构成员之间存在填充字节padding bytes,示例代码如下:示例代码一:
#include<stddef.h>#include<stdio.h>structaddress {charname;intphone;charstreet;};intmain(){printf("address 结构中的 name 偏移 = %ld 字节\n", offsetof(structaddress, name));printf("address 结构中的 phone 偏移 = %ld 字节\n", offsetof(structaddress, phone));printf("address 结构中的 street 偏移 = %ld 字节\n", offsetof(structaddress, street));return(0);}
运行结果如下:
root@52coder:~/workspace# gcc -g -o offset offset.croot@52coder:~/workspace# ./offsetaddress 结构中的 name 偏移 =0字节address 结构中的 phone 偏移 =4字节address 结构中的 street 偏移 =8字节
示例代码二:
#include<stddef.h>#include<stdio.h>structaddress {charname;charstreet;intphone;};intmain(){printf("address 结构中的 name 偏移 = %ld 字节\n", offsetof(structaddress, name));printf("address 结构中的 street 偏移 = %ld 字节\n", offsetof(structaddress, street));printf("address 结构中的 phone 偏移 = %ld 字节\n", offsetof(structaddress, phone));return(0);}
执行结果:
root@52coder:~/workspace# ./offset address 结构中的 name 偏移 =0字节address 结构中的 street 偏移 =1字节address 结构中的 phone 偏移 =4字节
如果有想学习c++的程序员,可来我们的C/C++学习扣qun:589348389,
微信公众号:java大世界(现在是发布c++学习干货哦,没有java)
免费送C++的视频教程噢!
我每晚上8点还会在群内直播讲解C/C++知识,欢迎大家前来学习哦。