So my idea:
A 2-D array is an array of arrays. If an array is X by Y, then each X points to an array with length Y. Is that part correct? Is that why also when you want to dynamically allocate an array in C you have to say
array=(type **)malloc(X*sizeof(type *)).
The type *
is to tell the compiler that each array index will be a pointer to another array so it should be sufficiently big enough to hold pointers o array?
Also why is this loop needed?
for(i =0;i<X;i++)
{
array[i]=(type *)malloc(Y*sizeof(type))
}
Is the cast
(type *)
needed because so that each index is a pointer to a 1-D array? But this time in the malloc
we can just say (type) instead of (type *)
because the index won't be holding pointers any more?
EDIT
Oh..so this is just mimicking a 2-d array by having an each index in an 1-d array point to another 1-d array. Ok. In that case is my logic for why each malloc have that specific argument make sense? The code here is taken from this SO question dynamic allocation/deallocation of 2D & 3D arrays