I encountered a problem in reading a piece of C code. 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. I know what this function is for, but i can't understand the meaning of " ((Struct*)0)
".
I will appeaciate If you can give me some explanation:).
The constant value 0
qualifies as a null pointer constant . The expression (Struct*)0
is therefore casting that null pointer constant to a pointer of type Struct *
. The expression then gets the Attribute
member.
Attempting to evaluate ((Struct*)0)->Attribute
would result in a null pointer defererence, however this expression is the argument to the sizeof
operator. 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.
It's casting a null pointer to the Struct*
type so it can determine the size of the attribute of that 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.
At least for C++, this is useful because unlike a non-pointer-based:
sizeof(Struct{}.Attribute)
it doesn't require Struct
to have a default constructor. 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.
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 sizeof
operator. Since sizeof
is a compile time operation, the NULL dereference never actually executes at runtime.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.