Reputation: 87
Basically my question is, when I run these two segments of code, I get different memory addresses. The first segment of code gives a certain memory address for rValue, and the second gives a different memory address for rValue, just by adding a & operator. Why does this happen?
#include <iostream>
using namespace std;
int pMem(int *rValue){
cout << "Value of rValue is " << *rValue << endl;;
cout << "Address of rValue is " << rValue << endl;
*rValue = 15;
cout << "Value of rValue now is " << *rValue << endl;
cout << "Address of rValue is " << rValue << endl;
return *rValue;
}
int main() {
int value = 8;
int *pValue = &value;
pMem(&value);
cout << "Value = " << value << endl;
cout << "Address of Value: " << pValue << endl;
cout << "Value at memory address " << pValue << ": " << *pValue << endl;
return 0;
}
2nd block of code, this time with the &rValue... I get a different memory address than the first block of code.
#include <iostream>
using namespace std;
int pMem(int *rValue){
cout << "Value of rValue is " << *rValue << endl;;
cout << "Address of rValue is " << &rValue << endl;
*rValue = 15;
cout << "Value of rValue now is " << *rValue << endl;
cout << "Address of rValue is " << &rValue << endl;
return *rValue;
}
int main() {
int value = 8;
int *pValue = &value;
pMem(&value);
cout << "Value = " << value << endl;
cout << "Address of Value: " << pValue << endl;
cout << "Value at memory address " << pValue << ": " << *pValue << endl;
return 0;
}
Upvotes: 1
Views: 76
Reputation: 726489
The reason for this behavior is that pointers are passed by value. In other words, when your function receives a pointer-typed parameter rValue
like this
int pMem(int *rValue)
C++ allocates space for a brand-new variable of type int*
, complete with its own address in memory. This variable gets initialized from a pointer expression that you pass to pMem
. Other than that, it is a separate variable that behaves like a local variable to pMem
. In particular, any re-assignments of the parameter itself have no effect on the caller.
It is the address of that parameter variable that gets printed when you do this:
cout << &pValue << endl; // Prints a new address
If you would like to see the address that you passed to the function, print the pointer, not the address of it:
cout << pValue << endl; // Prints the address that you passed
Upvotes: 2
Reputation: 212
Even pointers themselves take up memory and have an address associated with them.
So &rValue is the address of the the pointer rValue, and, unless it's a pointer to a function, that address will be different.
Upvotes: 3