Friday, 15 May 2020

2D Array in C++


There are multiple ways to create 2D arrays in C++.

The important thing to note it there could be below cases:


  1. Rows known at compile time but column unknown
  2. Rows unknown at compile time but column unknown


  • Rows known at compile time but column unknown

int r=3,c;
 int *arr[r];    //Valid configuration

/*
  now from some where we have received no of columns 
      i.e.   c = func();
*/
    for (i=0; i<r; i++) 
         arr[i] = (int *)malloc(c * sizeof(int)); 

  • Rows unknown at compile time but column unknown
int **arr;
int c,r;

/*
  now from some where we have received no of columns 
      i.e.   c = func1();  r  = func2();
*/

int **arr = (int **)malloc(r*sizeof(int *));

for(int i=0;i<c;i++){
 arr[i] = (int *)malloc(c*sizeof(c));
}






No comments:

Post a Comment