Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer with same memory address with different value

Tags:

c++

I casted the memory address from double to an integer . Even though they point to the same address why the values are 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 the value are different

0x7fff5fbff660
0x7fff5fbff660
0
2.5
Program ended with exit code: 0
like image 837
Hariom Singh Avatar asked Jul 30 '17 22:07

Hariom Singh


People also ask

Can two variables have the same memory address?

You cant have variables stored in the same memory address. You can point to a memory address and store the value in that memory address to a different memory address. No YOU are wrong, that is not 2 variables at the same address, that is a variable and a reference to the same variable. A reference is not a variable.

Can 2 pointers point to the same address?

Yes, two pointer variables can point to the same object: Pointers are variables whose value is the address of a C object, or the null pointer.

What happens when one of two pointer variables that point to the same memory location is freed?

free() returns memory pointed to by a pointer back to the system. Thus if you have two pointers - once free is called the memory is returned to the system.

Do pointers have their own memory address?

The main feature of a pointer is its two-part nature. The pointer itself holds an address. The pointer also points to a value of a specific type - the value at the address the point holds.


2 Answers

Suppose you have "11" written on a piece of paper. That is eleven if it's decimal digits. That is two if there's one mark for each value. That's three if it's binary. How you interpret stored information affects the value you understand it to be storing.

like image 101
David Schwartz Avatar answered Oct 04 '22 00:10

David Schwartz


double d = 2.5;
auto p = (int*)&d;
auto q = &d;

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

When you create

auto p = (int*)&d;

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

So the values of the pointers are the same, but the types are not.

When you print out

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

You are displaying the correct value - as it came in and out through that.

when you print out

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

You are looking at 4 (typically) bytes of the 8 byte memory, and interpreting them as an integer.

These happen to be 0x00, 0x00, 0x00, 0x00

like image 29
mksteve Avatar answered Oct 04 '22 02:10

mksteve