关键是参数的传递方式错了,下面是修改后的代码:
#include <new>
#include <iostream>
#include <cstdlib>
using namespace std;
template <class T>
bool Make2DArray(T **& p, const int row, const int column)
{
try{
// first step
p = new T*[row];
// second step
for (int i = 0; i < row ; i++)
p[i] = new int[column];
// work with it
for(int j = 0; j<row; j++)
for(int k = 0; k<column; k++)
*(*(p+j)+k) = (j+1)*(k+1);
return true;
}
catch(bad_alloc &ba)
{
cout<<ba.what()<<endl;
return false;
}
}
int main()
{
int ** a;
const int ROW = 2;
const int COLUMN = 3;
if(Make2DArray(a, ROW, COLUMN))
{
cout<<"succeeded in Memory allocation!"<<endl;
for(int i = 0; i<ROW; i++)
{
for(int j = 0; j<COLUMN; j++)
{
cout<<*(*(a+i)+j)<<" ";
}
cout<<endl;
}
cout<<endl;
}
else
cout<<"failed in Memory allocation!"<<endl;
if(a != NULL)
{
for(int i = 0; i<ROW; i++)
{
delete [](*(a+i));
}
delete [] a;
}
system("pause");
return 0;
}