C++ 二维数组/多维数组的动态分配(new)和释放(delete)
2015-05-28 14:07:19      个评论    来源：buxizhizhou530的专栏

# 1. 一维数组

```int *array1D;//假定数组长度为m

//动态分配空间
array1D = new int [m];

//释放
delete [] array1D;```

# 2. 二维数组

```//假定数组第一维长度为m， 第二维长度为n

//动态分配空间
```
`int **array2D = new int *[m];`
for( int i=0; i

P.S. 事实上二维数组空间的释放还可以更简单地用：delete [] array2D;

```//假设第一维长为m，第二维长为n

//动态分配空间
```
```int** array2D=new int*[m]; array2D[0]=new int[m*n]; for(int i=1;i//释放delete [] array2D[0];delete [] array2D;

3. 三维数组

int ***array3D;//假定数组第一维为m， 第二维为n， 第三维为h

//动态分配空间
array3D = new int **[m];
for( int i=0; i 4. 二维数组的一个例子

/*

0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
next
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
*/

#include stdafx.h
#include
#include
using namespace std;
// 在此处补充你的代码
class Array2
{
private:
int hang, lie;
int **iar;
public:
Array2() :hang(0), lie(0), iar(NULL) {}
Array2(int h, int l) :hang(h), lie(l)
{
iar = new int*[h];
iar[0] = new int[h*l];
for (int i = 1; i < h; ++i)
iar[i] = iar[i - 1] + l;
}
~Array2()
{
//cout << ;
if (iar != NULL)
{
delete[] iar;
}
}
int*& operator[](int m)
{
return iar[m];
}
const int operator() (int m, int n)
{
return iar[m][n];
}
Array2& operator=(const Array2& ar)
{
if (ar.iar == iar) return *this;
if (iar != NULL)
{
for (int i = 0; i < hang; ++i)
delete[] iar[i];
delete[] iar;
}
if (ar.iar != NULL)
{
hang = ar.hang;
lie = ar.lie;
iar = new int*[hang];
iar[0] = new int[hang*lie];
for (int i = 1; i < hang; ++i)
iar[i] = iar[i - 1] + lie;
for (int i = 0; i < hang; ++i)
for (int j = 0; j < lie; ++j)
iar[i][j] = ar.iar[i][j];
}
else
{
hang = 0;
lie = 0;
iar = NULL;
}
return *this;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
Array2 a(3, 4);
int i, j;
for (i = 0; i < 3; ++i)
for (j = 0; j < 4; j++)
a[i][j] = i * 4 + j;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; j++) {
cout << a(i, j) << ,;
}
cout << endl;
}
cout << next << endl;
Array2 b;
b = a;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; j++) {
cout << b[i][j] << ,;
}
cout << endl;
}

return 0;
}

```