0

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!

Ahmed Hadi
  • 121
  • 1
  • 3
  • 12
  • "a pointer to an int" a variable that can contain the address (where in memory you can find something) of an `int`. "a pointer to a pointer to an int" a variable that can contain the address of a variable that can contain the address of an `int`. The first answers the question "Where can I find an `int`?" the second answers the question "Where can I find where I can find an `int`?" – user4581301 Feb 02 '17 at 03:01
  • so it's not like pointer to an int mean an array of one dimension, and pointer to a pointer is an array of two dimensions ?!! – Ahmed Hadi Feb 02 '17 at 03:04
  • No, but they could be used like that if your code was written to treat the pointers as arrays. In that case, the address that each pointer holds is interpreted as the first element of an array. – David Scarlett Feb 02 '17 at 03:09

1 Answers1

3

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.

David Scarlett
  • 3,171
  • 2
  • 12
  • 28