Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 904
samoz Avatar asked Mar 18 '10 22:03

samoz


People also ask

What happens when static_cast fails?

As we learnt in the generic types example, static_cast<> will fail if you try to cast an object to another unrelated class, while reinterpret_cast<> will always succeed by "cheating" the compiler to believe that the object is really that unrelated class.

Can static_cast fail?

static_cast can't throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad - result is undefined.

Is static_cast a function?

static_cast is actually an operator, not a function.

When can you static cast?

This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.


1 Answers

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; 
like image 95
Jacob Avatar answered Oct 11 '22 23:10

Jacob