Help with Allocating Dynamic Arrays in C++


/* This little example program illustrates how to declare (and deallocate)
   dynamic 1D and 2D arrays in C++ */

#include <iostream.h>
#include <iomanip.h>

int main ()
{
        /* The 1D array is a pointer to an int. */
  int * Arr1D ;

        /* The 2D array is a pointer to a pointer to an int. */
  int ** Arr2D ;

  int W, H, i, j ;

  cout << endl ;
  cout << "Tell me the width:  " ;
  cin >> W ;
  cout << "Tell me the height:  " ;
  cin >> H ;

     /* Allocate an array of int's and make Arr1D a pointer to
        the base element of the array. */

  Arr1D = new int[W] ; 

     /* Allocate an array of pointers to int and make Arr2D a
        pointer to the base element of the array. */

  Arr2D = new int * [H] ; 


     /* For each row i of Arr2D (Arr2D[i]), allocate an array of
        int's and make Arr2D[i] a pointer to the base element of
        the array. */

  for (i=0; i<H; i++)
    Arr2D[i] = new int[W] ; 

     /* Put values in arrays. */

  for (j=0; j<W; j++) Arr1D[j] = j+1 ; // first the 1D array

  for (i=0; i<H; i++)                  // now the 2D array
      for (j=0; j<W; j++) 
        Arr2D[i][j] = i*W+j+1 ;

     /* Write the array values. */

  cout << endl << endl ;
  cout << "The 1D array:" << endl << endl ;       // first the 1D array 
  for (j=0; j<W; j++) cout << Arr1D[j] << "\t" ;  
  cout << endl << endl ;

  cout << "The 2D array:" << endl << endl ;      // now the 2D array
  for (i=0; i<H; i++)
  {
      for (j=0; j<W; j++) 
      {
        cout << Arr2D[i][j] << "\t" ;
      }
      cout << endl ;
  }
  cout << endl ;

       /* Deallocate the arrays */

  delete [ ] Arr1D ;
  for (i=0; i<H; i++) delete [ ] Arr2D[i] ;

  return 0 ;

}