What does it mean that a pointer is an address? It means that it refers to a memory location where the value pointing to is stored, usually a variable. When you say that a pointer points to something, you really mean a pointer pointing to a something variable.
This variable can hold an int, but it can as well hold another pointer. Thus more correctly, you have a pointer to a pointer variable. This makes the explanation easy: You need a pointer to a pointer variable for the same reasons you need a pointer to an integer variable.
A pointer to a pointer doesn't exist as its own type. If you have this:
int **p;
then p
ist still a single leveled pointer. Don't read it as this:
int (**)p; // wrong
but as this:
(int *) *p; // correct
because it is a pointer to another pointer variable that holds a pointer to an int variable.
int i = 125;
int *p1 = &i;
int **p2 = &p1;
Address Value
0x10000000 [0x20000000] p2
0x20000000 [0x30000000] p1
0x30000000 [125] i
EDIT:
If you still find this confusing, then don't try to think about the pointer to infinity. It works in plain C, is completely undefined behavior (and thus bad), and requires sizeof(unsigned int) == sizeof(unsigned int *)
. But then it works with any amount of *
the compiler supports.
unsigned int **********p;
p = (void *)&p;
printf("%x\n", **********p);
printf("%p\n", (void *)p);
int main(int argc, char **argv);
C#
has [under the hood] a pointer to pointervoid foo (ref myObject){...}
as opposed to using a single pointer -void foo (myObject){...}
. In the second case you can change the content ofmyObject
but not its address. In the first case you can also change the address ofmyObject
, say by doingmyObject = new MyObject()
. When passed by "ref" (pointer to a pointer), this address change will survive after the method is done. This is useful if you need to return multiple things and you hate using Tuples, because.Item1
,.Item2
,.Item3
do not help