描述:
M,N从用户那得到:
我想定义一个aa[M][N]的动态二维数组,
下面这样定义却不行,哪位大哥说说看:
long **aa;
for(j=0;j<M;j++)
aa[j] = (long *)malloc(N*sizeof(long));
要怎样定义呀???
解决方案1:
long **aa;aa = (long **)malloc(M * N * sizeof(long));
这种方法可以,
但用后一定要记得free(aa),
那也好办啊,举个例子:
//DynamicArray.cpp 动态二维数组
#include <iostream>
using namespace std;
int main()
{
int ** x;
int i,j,rows(2),cols(3);
try {
//创建
x = new int * [rows];
for (int i = 0 ; i < rows; i++) x[i] = new int [cols];
//初始化
for( i=0; i<2; i++)
{
for( j=0; j<3; j++)
{
x[i][j] = i + j;
cout << x[i][j] << " ";
}
cout << endl;
}
//释放
for(int i=0; i<rows; i++) delete [ ] x[i];
delete [ ] x;
x = 0;
}
catch (xalloc) {
cout << "create dynamic array caused error." << endl;
}
}
/*
运行结果:
0 1 2
1 2 3
*/
//创建--------------------------------
template<class T>
void Make2DArray(T ** &x, int rows, int cols)
{
x = new T * [rows];
for( int i=0; i<rows; i++) x[i]=new int[cols];
}
try
{
Make2DArray(x, r, c);
}
catch(xalloc)
{
cerr << "Create x caused error." << endl;
exit(1);
}
//删除-------------------------
template<class T>
void Delete2DArray(T** &x, int rows)
{
for(int i=0; i<rows; i++) delete [ ] x[i];
delete [ ] x;
x = 0;
}