1. 一维数组
对于简单的一维数组动态内存分配和释放,如下:
int *array1D;//假定数组长度为m //动态分配空间 array1D = new int [m]; //释放 delete [] array1D;
2. 二维数组
二维数组的动态分配和释放
//假定数组第一维长度为m, 第二维长度为n //动态分配空间 <pre name="code" class="cpp">int **array2D<span style="font-family: Arial, Helvetica, sans-serif;"> = new int *[m];</span>
for( int i=0; i<m; i++ ){ array2D[i] = new int [n] ;}//释放for( int i=0; i<m; i++ ){ delete [] arrar2D[i];}delete array2D;//我觉得应该是 delete [] array2D;
P.S. 事实上二维数组空间的释放还可以更简单地用:delete [] array2D;
二维数组的另一种分配和释放形式:
//假设第一维长为m,第二维长为n //动态分配空间 <pre name="code" class="cpp">int** array2D=new int*[m]; array2D[0]=new int[m*n]; for(int i=1;i<m;++i) array2D[i]=array2D[i-1]+n;
//释放delete [] array2D[0];delete [] array2D;
3. 三维数组
三维数组的动态分配和释放
int ***array3D;//假定数组第一维为m, 第二维为n, 第三维为h //动态分配空间 array3D = new int **[m]; for( int i=0; i<m; i++ ) { array3D[i] = new int *[n]; for( int j=0; j<n; j++ ) { array3D[i][j] = new int [h]; } } //释放 for( int i=0; i<m; i++ ) { for( int j=0; j<n; j++ ) { delete array3D[i][j];//觉得应该是 delete [] array3D[i][j]; } delete array3D[i];//觉得应该是 delete [] array3D[i]; } delete array3D;//觉得应该是 delete [] array3D;
4. 二维数组的一个例子
其中的析构函数用到了delete,构造函数用到了new进行分配。
// W4-课程作业-填空题1-3.cpp : Defines the entry point for the console application. /* 写一个二维数组类 Array2,使得下面程序的输出结果是: 输入 无 输出 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 <iostream> #include <cstring> 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[0]; //delete的方式要对,不然就会出现_Block_Type_Is_Valid (pHead->nBlockUse) Error 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; }
参考:http://www.cnblogs.com/Sylla-Zhang/archive/2012/10/08/2715300.html
c++ 二维数组new小结 主要讲各种形式的优缺点
时间: 2024-10-13 19:27:25