前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OFFSet_offtheroad

OFFSet_offtheroad

作者头像
全栈程序员站长
发布2022-09-23 10:03:27
4230
发布2022-09-23 10:03:27
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君

#define offsetof(s,m) (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))

该宏用于求结构体中一个成员在该结构体中的偏移量。第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName s中成员memberName(m)的偏移量。偏移量是size_t类型的。

offsetof returns the offset in bytes of the specified member from the beginning of its parent data structure. It is undefined for bit fields.

示例

代码语言:javascript
复制
#include <stdio.h>
#include <stddef.h>
typedef struct
{
int iVal;
int iVal2;
}Test;
typedef struct
{
char ch;
int iNum;
}Test2;
int main(void)
{
Test t = {1, 2};
Test2 t2 = {'t', 100};
printf("\naddress of t : %p\naddress of t.iVal : %p\naddress of t.iVal2: %p\n\n", &t, &(t.iVal), &(t.iVal2));
printf("offset of iVal in t: %p\n", offsetof(Test, iVal));
printf("offset of iVal2 in t: %p\n", offsetof(Test, iVal2));
printf("\naddress of t2 : %p\naddress of t2.ch : %p\naddress of t2.iNum: %p\n\n", &t, &(t2.ch), &(t2.iNum));
printf("offset of ch in t2: %p\n", offsetof(Test2, ch));
printf("offset of iNum in t2: %p\n", offsetof(Test2, iNum));
return 0;
}
wps_clip_image-31628
wps_clip_image-31628

  注意内存对齐。

原文

http://www.cppblog.com/lovedday/archive/2007/09/24/32801.html

http://baike.baidu.com/view/5513779.htm

转载于:https://www.cnblogs.com/mydomain/archive/2013/06/02/3114010.html

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172089.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档