top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

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

+2 votes
219 views

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

posted Oct 23, 2013 by Anuj Yadav

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

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 by Vikas Upadhyay
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 by Vikas Upadhyay
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.

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...