# How can we dynamically allocate contiguous memory to 2D array ??

246 views

What is the optimize way to allocate memory to 2D array dynamically ??

posted Oct 23, 2013

Lets you want to allocate memory for 3X4 2D array.
row = 3 column = 4
first allocate memory for rows.

``````int **array =NULL:
array =  (int**) malloc (sizeof(int*));

now allocate memory for matrix ;
int *ptr =-NULL;
ptr  = (int *)malloc (sizeof(int) X 3 X4)

for (i = 0; i< 3; i++)
array[i] = ptr + (i * 4);
``````

malloc is a complex. so we call it two times.
now memory for 2D array is contiguous.

``````#include<stdio.h>
#include<stdlib.h>
#define ROW 3
#define COL 4
int main()
{
int ** arr;
int * tmparr;
int i,j;
tmparr = malloc((ROW + ( ROW * COL))*sizeof(int));
arr = (int **) tmparr;

for (i=0;i<ROW;i++)
{
*(arr + i) = (tmparr + ROW + i * COL);
}

for (i = 0; i < ROW; i++)
for (j = 0; j < COL; j++)
arr[i][j] = (i + 1)*(1 +j);

for (i = 0; i < ROW; i++)
{
printf("\n");
for (j = 0; j < COL; j++)
printf("arr[%d][%d] = %d ", i, j, arr[i][j]);
}

return (0);
}
``````
Similar Questions
``````printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);