« Double pointers

Understand double pointers

Simplify Double Pointers

1int i = 10;
2int *p = &i;
3int **dp = &p;
4
5//same values for below 2 lines
6cout << "&p: " << &p << endl;
7cout << "dp: " << dp << endl;
8
9
10//same values for below 2 lines
11cout << "p: " << p << endl;
12cout << "*dp: " << *dp << endl;
13
14
15//same values for below 3 lines
16cout << "i: " << i << endl;
17cout << "*p: " << *p << endl;
18cout << "**dp: " << **dp << endl;

double_pointers.jpg

Above means p is a pointer to a int and dp is a pointer to int* which is a pointer. So dp is a double pointer

Passing double pointers to functions

1void increment1(int **p)
2{
3 p = p + 1;
4}

increment1.jpg

1void increment2(int **p)
2{
3 *p = *p + 1;
4}

increment2.jpg

1void increment3(int **p)
2{
3 **p = **p + 1;
4}

increment3.jpg

Final code:

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14void increment1(int **p)
15{
16 p = p + 1;
17}
18
19void increment2(int **p)
20{
21 *p = *p + 1;
22}
23
24void increment3(int **p)
25{
26 **p = **p + 1;
27}
28
29int main()
30{
31 int i = 10;
32 int *p = &i;
33 int **dp = &p;
34
35 cout << "&dp: " << &dp << endl;
36
37 // same values for below 2 lines
38 cout << "&p: " << &p << endl;
39 cout << "dp: " << dp << endl;
40
41 // same values for below 2 lines
42 cout << "p: " << p << endl;
43 cout << "*dp: " << *dp << endl;
44
45 // same values for below 3 lines
46 cout << "i: " << i << endl;
47 cout << "*p: " << *p << endl;
48 cout << "**dp: " << **dp << endl;
49
50 return 0;
51}