动态二维数组的连续创建
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几种应用方法点评
相关文章推荐
- 邂逅uGet,一个令人惊奇的Linux下载管理器
- 使用npm制作nodejs模块包
- C++中explicit关键字的作用
- openstack shelve/unshelve/stop浅析
- sublime text3下使用TAG快捷键ctrl+alt+f失效的解决方法
- windows无法设置防火墙
- 6个奇葩的(hello,world)C语言版(转)
- 看AngularJS
- 8-2-Time类中的运算符重载
- source insight快捷键及使用技巧
- iperf
- What is a good HEX editor on Linux?
- LVS集群的基础概念篇
- Linux 单网卡多 IP 的配置方法
- python__name= == '__main__'解析
- 分布式架构关键技术
- Linux 单网卡多 IP 的配置方法
- Jenkins slave远程运行windows exe无窗口问题解决方法
- Android Framework中的PolicyManager简介
- 为什么jQuery要返回jQuery.fn.init对象