Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a pointer to a pointer (int **a)?

Tags:

c++

pointers

int **a = malloc2d(M, N) // dynamically allocates a 2D array

What is the purpose of having int **a vice int *a. I understand that pointers are needed for dynamic allocation but why have a pointer to a pointer?

For a 3-dimensional array would it be:

int ***a

?

like image 415
Brandon Tiqui Avatar asked Feb 01 '10 05:02

Brandon Tiqui


1 Answers

You need a pointer to a pointer for several reasons.

In the example you gave, a double pointer is used to store the 2D array.

A 2D array in C is treated as a 1D array whose elements are 1D arrays (the rows).

For example, a 4x3 array of T (where "T" is some data type) may be declared by: "T mat[4][3]", and described by the following scheme:

                       +-----+-----+-----+
  mat == mat[0]   ---> | a00 | a01 | a02 |
                       +-----+-----+-----+
                       +-----+-----+-----+
         mat[1]   ---> | a10 | a11 | a12 |
                       +-----+-----+-----+
                       +-----+-----+-----+
         mat[2]   ---> | a20 | a21 | a22 |
                       +-----+-----+-----+
                       +-----+-----+-----+
         mat[3]   ---> | a30 | a31 | a32 |
                       +-----+-----+-----+

Another situation, is when you have pass a pointer to a function, and you want that function to allocate that pointer. For that, you must the address of the pointer variable, hence a pointer to a pointer

void make_foofoo(int** change) {
    *change = malloc(4);
}
like image 163
Amirshk Avatar answered Oct 31 '22 17:10

Amirshk