[英]What does ((Struct*)0) Mean?
I encountered a problem in reading a piece of C code.我在读取一段 C 代码时遇到了问题。 code show as below:
代码显示如下:
#define size_of_attribute(Struct, Attribute) sizeof(((Struct*)0)->Attribute)
The function of this macro function is gets the length of the attribute in the struct.这个宏 function 的 function 是获取结构中属性的长度。 I know what this function is for, but i can't understand the meaning of "
((Struct*)0)
".我知道这个 function 是做什么用的,但我无法理解“
((Struct*)0)
”的含义。
I will appeaciate If you can give me some explanation:).如果你能给我一些解释,我会安抚:)。
The constant value 0
qualifies as a null pointer constant .常量值
0
有资格作为null 指针常量。 The expression (Struct*)0
is therefore casting that null pointer constant to a pointer of type Struct *
.因此,表达式
(Struct*)0
将 null 指针常量转换为Struct *
类型的指针。 The expression then gets the Attribute
member.然后表达式获取
Attribute
成员。
Attempting to evaluate ((Struct*)0)->Attribute
would result in a null pointer defererence, however this expression is the argument to the sizeof
operator.尝试计算
((Struct*)0)->Attribute
将导致 null 指针延迟,但是此表达式是sizeof
运算符的参数。 This means the expression is not actually evaluated but simply examined to determine its type.这意味着表达式实际上并没有被评估,而是简单地检查以确定它的类型。
So sizeof(((Struct*)0)->Attribute)
gives you the size of the Attribute
member of the struct named Struct
without having to have an object of that type.因此
sizeof(((Struct*)0)->Attribute)
为您提供名为Struct
的结构的Attribute
成员的大小,而不必具有该类型的 object。
It's casting a null pointer to the Struct*
type so it can determine the size of the attribute of that struct.它将 null 指针转换为
Struct*
类型,因此它可以确定该结构的属性的大小。 Normally, reading an attribute from NULL
is illegal, but for sizeof
, it doesn't actually read anything, it just looks at the definition of the struct to determine the statically defined size of the attribute of any such struct.通常,从
NULL
读取属性是非法的,但对于sizeof
,它实际上并没有读取任何内容,它只是查看结构的定义以确定任何此类结构的属性的静态定义大小。
At least for C++, this is useful because unlike a non-pointer-based:至少对于 C++,这很有用,因为与非基于指针的不同:
sizeof(Struct{}.Attribute)
it doesn't require Struct
to have a default constructor.它不需要
Struct
具有默认构造函数。 A pointer can be made with no knowledge of how to construct the object, while an actual object (even if none is actually constructed) must still be constructed in a valid way, and you can't say with any reliability how an arbitrary struct
can be legally constructed.可以在不知道如何构造 object 的情况下创建指针,而实际的 object(即使实际上没有构造)仍然必须以有效的方式构造,并且您不能可靠地说任意
struct
如何合法建造。
This is basically accessing a member variable type without actually mentioning / creating any variable of that structure type.这基本上是在没有实际提及/创建该结构类型的任何变量的情况下访问成员变量类型。
Here,这里,
0
is casted to the structure type pointer, and 0
被强制转换为结构类型指针,并且sizeof
operator.sizeof
运算符的操作数。 Since sizeof
is a compile time operation, the NULL dereference never actually executes at runtime.由于
sizeof
是编译时操作,因此 NULL 取消引用从未在运行时实际执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.