Alex Rivera | Logout

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

Asked 2010-03-18T22:01:12.643
23

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*?

Edit
Report

1 Answer

1

You can convert between a double and an int with static_cast<>, but not between pointers to different types. You can convert any pointer type to or from void * with static_cast<>.

The rationale may be that int * and double * are often effectively arrays, and the implementation doesn't know how big the array is.

answered 2010-03-18T22:06:06.473

Your Answer