最近,我看到了一些很酷的东西。
#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/