GILGAMESH
GILGAMESH

Reputation: 1856

Casting double* to int* in C++

The title's pretty self explanatory. I want to cast a type double * into a type int *. I realize that I can use the C-type cast (int *) to do what I want, but is there a way to do this cast using C++ type casting i.e. static_cast etc?

Upvotes: 2

Views: 1454

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308158

You need to use reinterpret_cast<int *>(ptr).

I hope you really know what you're doing though. There's very little reason to do such a cast, especially when it's likely a double and an int are different sizes.

Upvotes: 5

templatetypedef
templatetypedef

Reputation: 372784

You can perform this cast using a reinterpret_cast:

int* veryUnsafePointer = reinterpret_cast<int*>(myDoublePointer);

Be aware that this does not give you back an integer representation of the double being pointed at; instead, the integer's value will be dependent on the binary representation of the double and the endianness of the system.

Hope this helps!

Upvotes: 5

Related Questions