How to allocate memory for a multidimensional array dynamically?

Many times we need to allocate memory for a multidimensional array dynamically. Because of complexity of pointers many find this difficult.

Following program allocates memory for a 3 x 3 array dynamically, copies contents of a 3 x 3 array in it and prints the contents using the pointer.

#include <iostream.h>
#include <new.h>
int a[ ][3] = {
                      1, 2, 3,
                      4, 5, 6,
                      7, 8, 9
                  };
void main( )
{
     int **p;
     p = new int *[3] ;
     for ( int i = 0 ; i < 3 ; i++ )
            p[i] = new int[3];
     for ( i = 0 ; i < 3 ; i++ )
       for ( int j = 0 ; j < 3 ; j++ )
            p[i][j] = a[i][j] ; 
     for ( i = 0 ; i < 3 ; i++ )
     {
       for ( j = 0 ; j < 3 ; j++ )
            cout << p[i][j] ;
      cout << "\n" ;
     }
}

1 comment: