Use double pointers to control pointers outside of functions

dbl_ptr_1

First we have a variable mainInt which has the value 45 and an address.
By definition, a pointer’s value is an address. And a pointer’s address is just some address.

Hence,

1) intPtr’s value, by definition, MUST be an address. In our case, it is the address of mainInt. 0x7fff5fbff86c
2) intPtr’s address is just some address. 0x7fff5fbff860
2) Dereferencing intPtr means we “get the value associated with the address value of intPtr”. The value is 45.

where

So basically, the function definition dblPtr has a double pointer parameter called paramPtr.

1) First, we look at the function call. Since the parameter is a double int pointer called paramPtr, it needs to point to an address of an int pointer. So we give it the address of intPtr, which is 0x7fff5fbff860.

2) Then, for the function defintion’s parameter, we draw a double pointer called “paramPtr” that will point to the address of intPtr given in the function call in step 1.

3) Thus, going into line 1 of dblPtr, we have everything set up as shown in the image.

dbl_ptr_2

What this means is that we dereference paramPtr, which gives us *paramPtr, which will move intPtr itself because we are using a dereference of it. When do:

we get the intPtr and point it to a newly allocated int variable on the heap. That int variable has the value 6969.

dbl_ptr_3

Hence, after the function call, in our specific case, we’d get:

after function call: *intPtr: 6969
after function call: intPtr: 0x100103ad0
after function call: &intPtr: 0x7fff5fbff860

Note that only intPtr would change from pointing to mainInt, to pointing to heap variable 6969. If there were other pointers pointing to mainInt, they would still be pointing there.

Full Source and Sample Output

SAMPLE OUTPUT:

before function call: address of variable mainInt: 0x7fff5fbff83c
before function call: value of variable mainInt: 45
before function call: *intPtr: 45
before function call: intPtr: 0x7fff5fbff83c
before function call: &intPtr: 0x7fff5fbff830
paramPtr is: 0x7fff5fbff830
&paramPtr is: 0x7fff5fbff688
*paramPtr is: 0x7fff5fbff83c
paramPtr is now: 0x7fff5fbff830
*paramPtr is now: 0x100103ad0
**paramPtr is now: 6969
after function call: value of variable mainInt: 45
after function call: address of variable mainInt: 0x7fff5fbff83c
after function call: *intPtr: 6969
after function call: intPtr: 0x100103ad0
after function call: &intPtr: 0x7fff5fbff830
after function call: *temp: 45
after function call: temp: 0x7fff5fbff83c
after function call: &temp: 0x7fff5fbff828