Monday, January 26, 2009

Allocating multi-dimensional arrays in CPP

template
T **AllocateDynamicArray( int nRows, int nCols)
{
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ )
      dynamicArray[i] = new T [nCols];

      return dynamicArray;
}


template
void FreeDynamicArray(T** dArray)
{
      delete [] *dArray;
      delete [] dArray;
}

int main()
{
      int **my2dArr = AllocateDynamicArray(4,4);
      my2dArr[0][0]=5;
      my2dArr[2][2]=8;
      cout << my2dArr[0][0] << " "<<< endl;
      cout << my2dArr[1][1] <<  " "<<< endl;
 
      FreeDynamicArray(my2dArr);
      getch();
      return 0;
}


Similarly for 3 d array:

No comments:

Post a Comment