堆上的 C++ 多维数组 [英] C++ Multi-dimensional Arrays on the Heap

查看:47
本文介绍了堆上的 C++ 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何动态分配多维数组?

How would I go about dynamically allocating a multi-dimensional array?

推荐答案

如果你已经知道嵌套维度的大小,你也可以直接使用 new 分配一个多维数组:

If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:

typedef int dimensions[3][4];

dimensions * dim = new dimensions[10];
dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42;
delete [] dim;

代替 10,可以传递运行时确定的值.因为它不是类型运算符 new 返回的一部分,所以这是允许的.例如,如果您知道列数,但想要保持行数可变,这很好.typedef 使代码更易于阅读.

instead of 10, a runtime determined value can be passed. Since it's not part of the type operator new returns, that's allowed. This is nice if you know the number of columns, but want to keep the number of rows variable, for example. The typedef makes it easier to read the code.

这篇关于堆上的 C++ 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆