c - 为什么将零转换为指针类型并访问其成员工作?

标签 c gcc

最近,我看到了一些很酷的东西。

#define container_of(ptr, type, member) ({                      \
const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
(type *)( (char *)__mptr - offsetof(type,member) );})

基本上,我知道这个宏的作用。但有一点我不明白。

为什么我们可以将0转换为指针类型(struct)并访问其成员?我已经referenced一些类似的东西和 0 看起来像一个空指针。那么为什么我们可以转换一个空指针然后访问它的成员呢?

最佳答案

typeof 是一个 gcc 扩展。该运算符的结果是类型名称。

这是有效的,因为它的操作数是在编译时计算的,因此指针实际上不需要指向任何东西。 documentation for this operator状态:

The operand of typeof is evaluated for its side effects if and only if it is an expression of variably modified type or the name of such a type.

由于 struct 不能包含可变长度数组,这保证 typeof( ((type *)0)->member ) 在运行时不会被评估时间,所以这是一个安全的操作。

关于c - 为什么将零转换为指针类型并访问其成员工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60040039/

相关文章:

c - 如何在执行进程之前等待子子进程和父进程?

c++ - 从 macports (macOS) 安装 gcc 8 的 gdb libstdc++ pretty-print 中的错误

c++ - 使用 Valgrind 的 std::fpclassify for long double 的错误结果

c - 在裸机程序中使用程序库

c++ - AVX 内在澄清,4x4 矩阵乘法奇数

c - 内存分配和复制到新结构

c - 使用数组读取文件

c - ndisasm手册中提到的二进制文件和可执行文件有什么区别?

c++ - 写入用户定义的 .txt 文件

gcc - 如何通过 gcc 的确切名称链接库?