/* * Utility for creating 2D arrays of any type. * Note: Use a vector instead if you can, it's much safer. * * Author: Samuel A. Inverso * * License: * Use this code freely, it is distributed without warranty express or * implied. */ #include #include "MultiArrayUtilities.h" template T ** MultiArrayUtilities::create2DArray( int rows, int cols, T initial ) { T **result = new T*[rows]; // first create an array of pointers ints for( int i=0; i < rows; ++i ) { result[i] = new T[cols]; // second point every pointer to an array of // ints for( int j = 0 ; j < cols ; ++j ) { result[i][j] = initial; } } return result; } template void MultiArrayUtilities::delete2DArray( T** ary, int rows ) { while( rows-- ) { delete [] ary[rows]; } delete[] ary; } int main( int argc, char** argv) { int rows = 7; int cols = 5; float **ary = MultiArrayUtilities::create2DArray( rows , cols, 4.2 ); for( int i= 0; i < rows ; ++i ) { for( int j=0; j < cols ; ++j ) { std::cout << ary[i][j] << " "; } std::cout << "\n"; } MultiArrayUtilities::delete2DArray( ary, rows ); }