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

+2 votes
233 views

What is the optimize way to allocate memory to 2D array dynamically ?? posted Oct 23, 2013
Share this question

## 2 Answers

+2 votes

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. answer Oct 23, 2013
0 votes
``````#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);
}
`````` answer Dec 8, 2013
Similar Questions
+3 votes

Input: arr[] = {5, 5, 10, -10, -20, 40, 50, 35, -20, -50}
Output: 125 (40, 50, 35)

+4 votes
``````printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);
[Error] invalid operands to binary + (have 'struct name' and 'int')
``````

where ptr is a pointer to the structure and allocated dynamic memory using malloc. Any suggestion would be helpful.

Thanks in advance.