How do I declare a 2d array in C++ using new?(如何使用 new 在 C++ 中声明二维数组?)
问题描述
如何使用 new 声明二维数组?
例如,对于正常"数组,我会:
int* ary = new int[Size]
但是
int** ary = new int[sizeY][sizeX]
a) 不起作用/编译,b) 没有完成什么:
int ary[sizeY][sizeX]
会.
如果你的行长是编译时常量,C++11 允许
auto arr2d = new int [nrows][CONSTANT];
请参阅 中的示例.
How do i declare a 2d array using new?
Like, for a "normal" array I would:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
a) doesn't work/compile and b) doesn't accomplish what:
int ary[sizeY][sizeX]
does.
If your row length is a compile time constant, C++11 allows
auto arr2d = new int [nrows][CONSTANT];
See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new
as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.
Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).
Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
The above, for colCount= 5
and rowCount = 4
, would produce the following:
Don't forget to delete
each row separately with a loop, before deleting the array of pointers. Example in another answer.
这篇关于如何使用 new 在 C++ 中声明二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 new 在 C++ 中声明二维数组?


基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01