[英]Static_cast integer address to pointer
Why do you need a C-style cast for the following?为什么你需要一个 C 风格的演员来做以下事情?
int* ptr = static_cast<int*>(0xff); // error: invalid static_cast from type 'int'
// to type 'int*'
int* ptr = (int*) 0xff; // ok.
static_cast
can only cast between two related types. static_cast
只能在两个相关类型之间进行转换。 An integer is not related to a pointer and vice versa, so you need to use reinterpret_cast
instead, which tells the compiler to reinterpret the bits of the integer as if they were a pointer (and vice versa): 整数与指针无关,反之亦然,因此您需要使用reinterpret_cast
,它告诉编译器重新解释整数的位,就像它们是指针一样(反之亦然):
int* ptr = reinterpret_cast<int*>(0xff);
Read the following for more details: 阅读以下内容了解更多详情:
You need a C-style cast or directly the reinterpret_cast
it stands for when casting an integer to a pointer, because the standard says so for unrelated types. 在将一个整数转换为指针时,你需要一个C风格的转换或直接表示它所代表的reinterpret_cast
,因为标准对于不相关的类型是这样说的。
The standard mandates those casts there, because 该标准要求那些演员在那里,因为
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? 什么时候应该使用static_cast,dynamic_cast,const_cast和reinterpret_cast?
Regular cast vs. static_cast vs. dynamic_cast 常规演员与static_cast与dynamic_cast
Being late to the party I found that the following works only using static casts:迟到我发现以下作品仅使用 static 演员表:
int* ptr1 = static_cast<int*>(static_cast<void*>(static_cast<unsigned char*>(nullptr) + 0xff));
This way you don't translate the constant directly to a pointer, instead you add it as a bytewise offset to the nullptr.这样您就不会将常量直接转换为指针,而是将其作为字节偏移量添加到 nullptr。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.