First, we have a variable called aNum. That variable has an address, with an associated value:
1 |
int aNum = 100; |
We then have:
1 |
int * intPtr = &aNum; |
We have an integer pointer point to the address of our aNum variable.
Then we have a function definition:
1 2 3 4 5 6 |
void dereferenceTest(int * param) { std::cout << "nINSIDE: parameter pointer is DEREFERENCED...getting the original value"; *param = 45; std::cout << "nINSIDE: original value changed to: " << *param << std::endl; } |
We use that function like this:
1 |
dereferenceTest(intPtr); |
The function gets pushed onto the main function stack. The function returns void so we do not push any return variables onto the stack. Next, the function has
1 |
int * param |
as its parameter. Hence, that parameter gets pushed onto the stack like so:
The parameter variable param points to whatever intPtr is pointing to…which is aNum’s address.
In our function definition, param gets dereferenced. This means that it gets the value associated with the address that it is pointing to. In our case its the value of aNum, which is 100. It changes it to 45.
1 |
*parameterIntPtr = 45; |
When the function call ends, the whole function with its parameter list gets popped. All we’re left with is aNum, which value has been changed to 45.
the pointer numPtr which points to the address of aNum, and thus, also will get 45 if we dereference it.
Sample Output
OUTSIDE: int * intPtr is: 100
OUTSIDE: someNumber is: 100
INSIDE: parameter pointer is DEREFERENCED…getting the original value which is: 100
INSIDE: original value changed to: 45
OUTSIDE: int * intPtr is: 45
OUTSIDE: someNumber is: 45
full source
1 2 3 4 5 6 |
void dereferenceTest(int * parameterIntPtr) { std::cout << "nINSIDE: parameter pointer is DEREFERENCED...getting the original value which is: " << *parameterIntPtr; *parameterIntPtr = 45; std::cout << "nINSIDE: original value changed to: " << *parameterIntPtr << std::endl; } |
1 2 3 4 5 6 7 8 9 |
int main(int argc, const char * argv[]) { int someNumber = 100; int * intPtr = &someNumber; std::cout << "nOUTSIDE: int * intPtr is: " << *intPtr; std::cout << "nOUTSIDE: someNumber is: " << someNumber; dereferenceTest(intPtr); std::cout << "nOUTSIDE: int * intPtr is: " << *intPtr; std::cout << "nOUTSIDE: someNumber is: " << someNumber; |