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
?
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 4×3 array of T (where “T” is some data type) may
be declared by: “T mat[4][3]”, and described by the following
scheme:
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