C++: can't static_cast from double* to int*

samoz picture samoz · Mar 18, 2010 · Viewed 24.2k times · Source

When I try to use a static_cast to cast a double* to an int*, I get the following error:

invalid static_cast from type ‘double*’ to type ‘int*’

Here is the code:

#include <iostream>
int main()
{
        double* p = new double(2);
        int* r;

        r=static_cast<int*>(p);

        std::cout << *r << std::endl;
}

I understand that there would be problems converting between a double and an int, but why is there a problem converting between a double* and an int*?

Answer

Jacob picture Jacob · Mar 18, 2010

You should use reinterpret_cast for casting pointers, i.e.

r = reinterpret_cast<int*>(p);

Of course this makes no sense,

unless you want take a int-level look at a double! You'll get some weird output and I don't think this is what you intended. If you want to cast the value pointed to by p to an int then,

*r = static_cast<int>(*p);

Also, r is not allocated so you can do one of the following:

int *r = new int(0);
*r = static_cast<int>(*p);
std::cout << *r << std::endl;

Or

int r = 0;
r = static_cast<int>(*p);
std::cout << r << std::endl;