Spread the love

Following are different ways to create a 2D array on heap (or dynamically allocate a 2D array).

In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we created a 2D array with r = 3, c = 4 and following values

1    2    3    4
5   6    7     8
9  10  11   12

Method 1 :- Using a single pointer

 

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4;
    int *arr = (int *)malloc(r * c * sizeof(int));
 
    int i, j, count = 0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         *(arr + i*c + j) = ++count;
 
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", *(arr + i*c + j));
 
   /* Code for further processing and free the 
      dynamically allocated memory */
   
   return 0;
}

 

Method 2 :- Using an array of pointers

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4, i, j, count;
 
    int *arr[r];
    for (i=0; i<r; i++)
         arr[i] = (int *)malloc(c * sizeof(int));
 
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count
 
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", arr[i][j]);
 
    /* Code for further processing and free the 
      dynamically allocated memory */
 
   return 0;
}

 

Method 3 :- Using pointer to a pointer

 

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int r = 3, c = 4, i, j, count;
 
    int **arr = (int **)malloc(r * sizeof(int *));
    for (i=0; i<r; i++)
         arr[i] = (int *)malloc(c * sizeof(int));
 
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
 
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", arr[i][j]);
 
   /* Code for further processing and free the 
      dynamically allocated memory */
 
   return 0;
}

 

 

If you like this Article, then don’t forget to Click on Social likes buttons.