您的位置:首页 > 其它

动态二维数组的连续创建

2014-04-22 22:12 190 查看
#include <iostream>
using namespace std;

class X{
public:
X(int ii = 0): i(ii) {
cout << "build " << i << endl;
}
~X(){
cout << "destroy " << i << endl;
}
void assign(int ii){
i = ii;
}
void print() const{
cout << i << " ";
}
private:
int i;
};

int main()
{
int rows = 3;
int cols = 2;

cout << "********* allocate array: **********" << endl;
X** x_array = new X*[rows];// rows个X*数组
x_array[0] = new X[rows*cols];// 实际的连续内存
for(int i = 1; i < rows; i++){
x_array[i] = x_array[i-1] + cols;
}

cout << "********** assign value for array: ********** " << endl;
int index = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
x_array[i][j].assign(index++);
x_array[i][j].print();
}
cout << endl;
}

cout << "********** delete array: **********" << endl;
delete[] x_array[0];
delete[] x_array;

}


思路:

首先动态创建rows个X*数组x_array,之后在x_array[0]处创建一块连续内存,再把相应的行地址存储到x_array数组中。如下图:



这样,在访问二维数组时可以直接采用下标形式x_array[i][j]. 注意,在销毁数组时,要同时销毁x_array[0]和x_array处申请的内存。

上面代码执行结果如下:



参考: C++二维数组new几种应用方法点评
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: