5.5. Pointers to pointersΒΆ
A pointer can point to any memory address within the scope of the program, which includes pointers themselves. Each new pointer just adds another to the chain of pointers. The language does not impose a strict limit. The only limit is your sanity...
1#include <iostream>
2
3int main() {
4 int x = 8;
5
6 // all of these variables point to x
7 int* p2x = &x;
8 int** p2p = &p2x;
9 int*** p2pp = &p2p;
10
11 return 0;
12}
Like int or char, a pointer type is still a type.
When you declare a variable of type pointer,
storage still must be allocated somewhere,
and this storage must have an address too.
When dealing with pointers, we have to manage the added complexity of keeping clear in our minds the difference between the pointer variable and what the pointer points to. When dealing with pointers to pointers, we have to manage the pointer, what it points to, and what the pointer that it points to points to.
1#include <iostream>
2#include <string>
3
4using std::string;
5using std::cout;
6
7 int main() {
8 string message[] = {"Alice","Bob here!","Carol checking in."};
9
10 string *sp; // a pointer to at least 1 string
11
12 sp = message;
13 cout << "sp:\n";
14 cout << sp << '\n';
15 cout << *sp << '\n';
16 cout << *(sp + 1) << '\n';
17 cout << *(sp + 2) << "\n\n";
18
19
20 cout << "sp2:\n";
21 string *sp2 = new string [3]; //create string pointer on the heap
22 *sp2 = "\nAlice has left the building";
23 *(sp2 + 1) = "Bob who?";
24 *(sp2 + 2) = "Carol checked out.";
25
26 cout << sp2 << '\n';
27 cout << *sp2 << '\n';
28 cout << *(sp2 + 1) << '\n';
29 cout << *(sp2 + 2) << '\n' << '\n';
30
31 string **sp3; // a pointer to a string pointer
32
33 cout << "sp3:\n";
34 sp3 = &sp2;
35 cout << sp3 << '\n';
36 cout << **sp3 << '\n';
37 }
You can also define a pointer to a reference variable:
Open video
More to Explore
MyCodeSchool video: Pointers in C/C++ playlist