用一行代码实现宏offsetof

简介: 用一行代码实现宏offsetof

用一行代码实现宏offsetof

简介宏offsetof

offsetof (type,member)

type为类型名

member为成员名

作用:

  • This macro with functional form returns the offset value in bytes of member member in the data structure or union type type. The value returned is an unsigned integral value of type size_t with the number of bytes between the specified member and the beginning of its structure.——此具有函数形式的宏返回数据结构或联合类型类型中成员成员的偏移值(以字节为单位)返回的值是类型为 size_t 的无符号整数值,具有指定成员与其结构开头之间的字节数。
  • 简单来说,就是返回结构体成员相较于结构开头的偏移量(单位为字节)

例如:

#include <stdio.h>      /* printf */
#include <stddef.h>     /* offsetof */
struct foo {
  char a;
  char b[10];
  char c;
};
int main ()
{
  printf ("offsetof(struct foo,a) is %d\n",(int)offsetof(struct foo,a));
  printf ("offsetof(struct foo,b) is %d\n",(int)offsetof(struct foo,b));
  printf ("offsetof(struct foo,c) is %d\n",(int)offsetof(struct foo,c));
  return 0;
}

output:

offsetof(struct foo,a) is 0
offsetof(struct foo,b) is 1
offsetof(struct foo,c) is 11

模拟实现

要算出结构成员相较于结构开头的偏移量,这是不方便的。因为当我们只传入一个参数时,我们无法确定结构的起始地址。

但如果我们可以让起始地址为0,那么结构成员相较于起始地址的偏移量就是该成员的地址了。

因此我们可以这么写:

#define OFFSETOF(type,member) (size_t)&(((type *)0)->member)
  • 我们直接将地址0处强制转换为type类型,这样结构的起始地址就是0了
  • 接下来我们再引用结构成员,对其取地址,得到的也就是相较于结构开头的偏移量了
  • 最后将地址转换为size_t类型返回即可
相关文章
|
3月前
|
程序员 C语言 UED
详解C语言assert宏
详解C语言assert宏
26 0
|
1月前
|
编译器 C语言
C语言宏定义(#define定义常量​、#define定义宏​、 带有副作用的宏参数、 宏替换的规则、 宏函数的对比)
C语言宏定义(#define定义常量​、#define定义宏​、 带有副作用的宏参数、 宏替换的规则、 宏函数的对比)
|
28天前
|
编译器 C语言
【C语言】什么是宏定义?(#define详解)
【C语言】什么是宏定义?(#define详解)
25 0
|
30天前
|
C语言
typedef 和 # define 用法区别
typedef 和 # define 用法区别
19 0
|
2月前
|
Linux
offsetof宏与container_of宏
offsetof宏与container_of宏
12 0
|
3月前
|
C语言
详解C语言可变参数列表(stdarg头文件及其定义的宏)
详解C语言可变参数列表(stdarg头文件及其定义的宏)
48 0
|
4月前
|
编译器
#define 宏定义看这一篇文章就够了
#define 宏定义看这一篇文章就够了
116 0
|
6月前
|
C语言
C语言的offsetof宏模拟和用宏实现交换奇偶位
C语言的offsetof宏模拟和用宏实现交换奇偶位
|
11月前
|
C语言
c语言分层理解(#define定义宏)
c语言已经完结,有兴趣的可以收藏一下我的c语言专栏,感谢各位大佬支持! 1.宏是什么? #define 机制包括了一个规定,允许把参数替换到文本中,这种实现通常称为宏(macro)或定义 宏(define macro)。
121 0
|
C语言
C语言中typedef和define对比分析
C语言中typedef和define对比分析
83 0