i need to understand what is the difference between:
a pointer to an int
and
a pointer to a pointer to an int
i don't think the language matters but to be informed i'm taking c++.
Thanks!
i need to understand what is the difference between:
a pointer to an int
and
a pointer to a pointer to an int
i don't think the language matters but to be informed i'm taking c++.
Thanks!
Pointers are just memory address. So a pointer to an int means a variable whose value is the memory address of an int, and a pointer to a pointer to an int means a variable whose value is the memory address of a pointer to int, and the value of that pointer to int is a memory address of an int.
Let's say you define three variables as follows.
int a = 184; // Plain int, value 184.
int *b = &a; // Pointer to int, specifically pointing to a.
int **c = &b; // Pointer to pointer to int, which points to b, which points to a.
Here's what these variables might look like in memory. (Note that only the value is actually stored in memory. The type is inferred from the code that uses that memory.)
+------------+ +------------+ +------------+
type | int | | int* | | int** |
+------------+ +------------+ +------------+
address | 0x02618368 | | 0x02618372 | | 0x02618376 |
+------------+ <--- +------------+ <--- +------------+
value | 184 | | 0x02618368 | | 0x02618372 |
+------------+ +------------+ +------------+
So to get an int out of c
, you would need to dereference it twice. The first deference takes the value from c
, interprets it as the address of a pointer to int, and looks up that address to obtain a pointer to int, which is equal to b
. The second dereference takes the value from the resulting pointer to int, interprets it as the address of an int, and looks up that address to obtain an int, which is equal to a
.