Google News
logo
CPP - Interview Questions
How to dynamically allocate a 2d array in C++ ?
There are several methods by which one can allocate memory to 2D array dynamically one of which is as follows.
#include <iostream> 
int main() 
{ 
    int row = 2, col = 2; 
    int* a =  new int[row * col];
   
    int i, j, count = 0; 
    for (i = 0; i <  row; i++) 
      for (j = 0; j < col; j++) 
         *(a+ i*col + j) = count++; 
   
    for (i = 0; i <  row; i++) 
      for (j = 0; j < col; j++) 
         printf("%d ", *(a + i*col + j)); 
   
    delete[ ] a;
    return 0; 
} 

Output : 
0 1 2 3 

Advertisement