Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does same pointer has different addresses

Tags:

c++

pointers

class A{};

void Foo(A *p)
{ 
 std::cout << &p << std::endl; 
 std::cout << p << std::endl; 
}

int main()
{
 A *p = new A();
 std::cout << &p << std::endl;
 std::cout << p << std::endl;
 Foo(p);
}

The above program prints the same value for p but different addresses for &p. Can somebody please explain why ?

like image 333
jatniel Avatar asked Jun 21 '26 04:06

jatniel


2 Answers

The above program prints the same value for "p"

This is because one p is a copy of the other, so they both have the same value. The value of a pointer is a memory address where an object is stored so having the same value means pointing to the same object.

A function argument is a copy of the object that was passed to the function .

but different addresses for "&p". Can somebody please explain why ?

Each p here is a separate variable and a separate object ††. Both objects exist simultaneously. The C++ standard specifies that each currently existing object has a unique address †††, so therefore each p here must have a unique address.

The Unary operator & is the addressof operator, and it returns the memory address where the operand is stored.


Unless that function argument is a reference. In that case the reference is bound to the passed object. The p argument is not a reference.

†† Pointers themselves are objects. The memory address where a pointer stored is separate from the memory address that is its value which is the memory address of the pointed object.

††† There are exceptions in case of sub-objects, but those exceptions aren't relevant here.

like image 59
eerorika Avatar answered Jun 23 '26 17:06

eerorika


void Foo(A *p)
{ 
 std::cout << &p << std::endl; 
 std::cout << p << std::endl; 
}

When you pass something to Foo() that something is copied into p.So the actual parameter(the something which was passed) is not the same thing as the formal parameter(p here), though they will hold the same value. Inside Foo(), &p will print address of this formal parameter and not the address of the actual parameter that was passed.

And since the formal and actual parameter hold same value, p prints the same value.

like image 31
Gaurav Sehgal Avatar answered Jun 23 '26 19:06

Gaurav Sehgal