Search code examples
c++casting

Static_cast integer address to pointer


Why do you need a C-style cast for the following?

int* ptr = static_cast<int*>(0xff); // error: invalid static_cast from type 'int' 
                                    // to type 'int*'
int* ptr = (int*) 0xff; // ok.

Solution

  • static_cast can only cast between two related types. 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):

    int* ptr = reinterpret_cast<int*>(0xff);
    

    Read the following for more details:

    Type conversions