Hello.

Im interested in learning something about allocating memory for a 2d array.
So I have a function that does this, and it goes something like this :

``````short **g2D(short **arr,short row,short col)
{
short i;
arr=malloc(row*sizeof*arr);
if(!arr)
{
printf("\nMemory unavailable");
exit(EXIT_FAILURE);
}

for(i=MIN;i<row;i++)
{
arr[i]=malloc(col*sizeof*arr);

if(!arr)
{
printf("\nMemory unavailable");
exit(EXIT_FAILURE);
}
}
return arr;
}``````

And the function call

``2darray=g2D(2darray,row,col);``

I would like to know what does it mean when I use a pointer to pointer in function prototype and in function declaration, is this necessary and is there another way to allocate memory for a 2d array via function? I understand the fact that dimensions dont exist in memory.

Well, the function is basically allocating memory to a bunch of pointers. It can be shown like this:

``````[....] means allocate memory to a pointer.

ptr1 = [.....]
ptr2 = [.....]
ptr3 = [.....]
ptr4 = [.....]

This is done by
for(i=MIN;i<row;i++)
{
arr[i]=malloc(col*sizeof*arr);

if(!arr)
{
printf("\nMemory unavailable");
exit(EXIT_FAILURE);
}
}

_____________________________
ptr_ptr --> | ptr1 | ptr2 | ptr3 | ptr4 |
-----------------------------
This is done by
arr = malloc(row * sizeof(*arr));``````

Here, ptr_ptr has to be a pointer to a pointer. So, what we are doing is,

1) Allocate sizeof( pointer ) * 4 (4 pointers in the example)

2) Now, allocate memory for each of these pointers.

Well, the function is basically allocating memory to a bunch of pointers. It can be shown like this:

``````[....] means allocate memory to a pointer.

ptr1 = [.....]
ptr2 = [.....]
ptr3 = [.....]
ptr4 = [.....]

This is done by
for(i=MIN;i<row;i++)
{
arr[i]=malloc(col*sizeof*arr);

if(!arr)
{
printf("\nMemory unavailable");
exit(EXIT_FAILURE);
}
}

_____________________________
ptr_ptr --> | ptr1 | ptr2 | ptr3 | ptr4 |
-----------------------------
This is done by
arr = malloc(row * sizeof(*arr));``````

Here, ptr_ptr has to be a pointer to a pointer. So, what we are doing is,

1) Allocate sizeof( pointer ) * 4 (4 pointers in the example)

2) Now, allocate memory for each of these pointers.

``short **g2D``