I am very very new to c++ and can't get my head around the use of double, triple pointers etc.. What is the point of them?
The trick to understanding pointers in C is simply to go back to the basics, which you were probably never taught. They are:
- Variables store values of a particular type.
- Pointers are a kind of value.
- If
x
is a variable of type T
then &x
is a value of type T*
.
- If
x
evaluates to a value of type T*
then *x
is a variable of type T
. More specifically...
- ... if
x
evaluates to a value of type T*
that is equal to &a
for some variable a
of type T
, then *x
is an alias for a
.
Now everything follows:
int x = 123;
x
is a variable of type int
. Its value is 123
.
int* y = &x;
y
is a variable of type int*
. x
is a variable of type int
. So &x
is a value of type int*
. Therefore we can store &x
in y
.
*y = 456;
y
evaluates to the contents of variable y
. That's a value of type int*
. Applying *
to a value of type int*
gives a variable of type int
. Therefore we can assign 456 to it. What is *y
? It is an alias for x
. Therefore we have just assigned 456 to x
.
int** z = &y;
What is z
? It's a variable of type int**
. What is &y
? Since y
is a variable of type int*
, &y
must be a value of type int**
. Therefore we can assign it to z
.
**z = 789;
What is **z
? Work from the inside out. z
evaluates to an int**
. Therefore *z
is a variable of type int*
. It is an alias for y
. Therefore this is the same as *y
, and we already know what that is; it's an alias for x
.
No really, what's the point?
Here, I have a piece of paper. It says 1600 Pennsylvania Avenue Washington DC
. Is that a house? No, it's a piece of paper with the address of a house written on it. But we can use that piece of paper to find the house.
Here, I have ten million pieces of paper, all numbered. Paper number 123456 says 1600 Pennsylvania Avenue
. Is 123456 a house? No. Is it a piece of paper? No. But it is still enough information for me to find the house.
That's the point: often we need to refer to entities through multiple levels of indirection for convenience.
That said, double pointers are confusing and a sign that your algorithm is insufficiently abstract. Try to avoid them by using good design techniques.