2

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?

GILGAMESH
  • 1,816
  • 3
  • 23
  • 33

2 Answers2

5

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 2
    So it seems you want to read the internal representation of a `double`. Do you know that a `double` is most likely larger than an `int`? (On most systems 8 vs. 4 bytes) – leemes Oct 26 '13 at 01:35
  • Dereferencing the result of this cast has undefined behavior because of the [strict aliasing rule](https://stackoverflow.com/q/98650/3425536). – Emil Laine Sep 02 '17 at 09:20
5

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622