Home Theory How do pointers to pointers work in C?

How do pointers to pointers work in C?

by nikoo28
0 comment 3 minutes read

We generally see cases like:-

int *ptr = &x;

Here ptr is a pointer to a memory location of the variable x.

What if we do something like

int **ptr2 = &ptr;

What we did just now was made a pointer to a pointer. Now the question arises, what happens behind the scene?

Let’s assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses):

  45   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    | 58 |    |    | 63 |    | 55 |    |    | h  | e  | l  | l  | o  | \0 |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

What we can see here, is that at address 63 the string “hello” starts. So in this case, if this is the only occurrence of “hello” in memory then,

const char *c = "hello";

… defines c to be a pointer to the (read-only) string “hello”, and thus contains the value 63. c must itself be stored somewhere. In the above example it is at location 58. Of course we can not only point to characters, but also to other pointers. Example:-

const char **cp = &c;

Now cp points to c, that is, it contains the address of c (which is 58).
We can go even further. Consider:

const char ***cpp = &cp;

Now cpp stores the address of cp. So it has value 55 (based on the example above), and it is itself stored at address 60.

WHY DO WE NEED THEM?

  • The name of an array usually yields the address of its first element. So if the array contains elements of type t, a reference to the array has type t *. Now consider an array of arrays of type t: naturally a reference to this 2D array will have type (t *)* = t **, and is hence a pointer to a pointer.
  • Even though an array of strings sounds one-dimensional, it is in fact two-dimensional, since strings are character arrays. Hence: char **.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More