Pointer with the same memory address with different value

I chose the memory address from double to integer. Even if they point to the same address, why are the values ​​different?

#include<iostream> using namespace std; int main() { double d = 2.5; auto p = (int*)&d; auto q = &d; cout<<p<<endl; // prints memory address 0x7fff5fbff660 cout<<q<<endl; // print memory address 0x7fff5fbff660 cout<<*p<<endl; //prints 0 cout<<*q<<endl; // prints 2.5 return 0; } 

But why different meanings

 0x7fff5fbff660 0x7fff5fbff660 0 2.5 Program ended with exit code: 0 
+7
c ++
source share
6 answers
 double d = 2.5; auto p = (int*)&d; auto q = &d; 

p and q are created by pointing to the same memory location. The memory contains double (usually 8 bytes)

While creating

 auto p = (int*)&d; 

you tell the compiler ( reintepret_cast< int*> ( &d) ) that the value in d was an integer.

Pointer values ​​are the same, but types are not.

When you print

 cout<<*q<<endl; // prints 2.5 

You show the correct value - as it appears and exits.

when printing

 cout<<*p<<endl; //prints 0 

You look at 4 (usually) bytes of 8-byte memory and interpret them as an integer.

It will be 0x00, 0x00, 0x00, 0x00

+6
source share

Suppose you have "11" written on a piece of paper. It is eleven if it is decimal digits. These are two if there is one mark for each value. These are three if it is binary. How you interpret stored information affects the value that you understand to store it.

+9
source share

This is because you violated the strict alias rule by giving you undefined behavior. You cannot use type A through a pointer to type B and just pretend that it works.


TL; DR:

if you have an int* pointing to some memory containing an int , and then you point a float* to that memory and use it as a float , you break edit. If your code does not comply with this, then the Optimizer compiler is likely to break your code.

+7
source share

The memory addresses are the same, and both of them point to a double-precision floating-point number in memory. However, you asked the compiler to treat it as a whole, and the other as a double. (The pointer may simply be a memory address, but the compiler also has type information at compile time.) It so happens that the representation in this area with double precision looks like 0 when viewed as an integer.

+3
source share

Because you yourself scribbled them into different types.

0
source share

When you do auto p = (int*)&d; , you ask the compiler to keep the double value in the memory area allocated for the integer. The whole and the double are presented in different formats in the computer's memory. The double is stored using the view in memory, but int is not. This is a classic example of undefined behavior.

-2
source share

All Articles