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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,417 times
        
    2
            
            
         
    
    
        GILGAMESH
        
- 1,816
- 3
- 23
- 33
- 
                    3Why do you want to do this? Do you want to turn a double into an int? – Christian Ternus Oct 26 '13 at 01:31
- 
                    2As other pointed you will not cast a value this way. Even if it's not what you want, your code might not work because of strict aliasing rules. – j_kubik Oct 26 '13 at 01:37
- 
                    Another way to do something similar is to make a union with a double and int. – brian beuning Oct 26 '13 at 02:26
2 Answers
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
- 
                    2So 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