1 //Creating a 2-D dynamic array using templates and new2 3#include <iostream>4#include <exception>5#include <cstdlib>6#include <iomanip>7 using namespacestd;8 9template<classType>Ten BOOLMake2darray (Type **&x,intRowsintcols) One { A inti; - Try - { the //Create a row pointer -x=NewType *[rows]; - //allocate space for each row - for(i=0; i<rows;i++) + { -x[i]=NewType [cols]; + } A return true; at } - Catch(Bad_alloc) - { - return false; - } - in } - to intMain () + { - int**x,rows,cols,i,j; the BOOLFlag; *cout<<"Enter the number of rows to create a dynamic array rows="; $Cin>>rows;Panax Notoginsengcout<<"Enter the number of columns to create a dynamic array cols="; -Cin>>cols; theflag=Make2darray (x,rows,cols); + if(flag==true) A { the for(i=0; i<rows;i++) + { - for(j=0; j<cols;j++) $ { $x[i][j]=j+i*cols; - } - } the } -cout<<"output created array: \ n";Wuyi for(i=0; i<rows;i++) the { - for(j=0; j<cols;j++) Wu { -COUT<<SETW (3) <<X[i][j]; About } $cout<<Endl; - } - return 0; -}
Debug Run Result:
Using templates in C + +, New creates 2-D dynamic arrays