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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With