简体   繁体   English

在 C++ 中初始化具有未知第一维大小的二维数组

[英]Initialize a 2d array with unknown first dimension size in C++

Say I need a 2d array, first dimension size set at runtime, and second dimension size is set to 5 at compilation time.假设我需要一个二维数组,第一维大小在运行时设置,第二维大小在编译时设置为 5。

Since we can do this to initialize a 1d array with unknown size因为我们可以这样做来初始化一个未知大小的一维数组

int* arr;
arr = new int[12];

I would like to make the following code work我想让以下代码工作

int* arr[5];
arr = new int[12][5];

Notice:注意:

I need the second dimension set to 5, not first dimension.我需要将第二维设置为 5,而不是第一维。 So I need to be able to do arr[11][4] but not arr[4][11] .所以我需要能够做arr[11][4]而不是arr[4][11]

I know I can make arr an int** and then assign a 2d array to arr, so please avoid such answer.我知道我可以将arr设为int** ,然后为 arr 分配一个二维数组,所以请避免这样的答案。

I know I can use STL containers such as vector, so please avoid such answer.我知道我可以使用 STL 容器,例如 vector,所以请避免这样的回答。

You can write:你可以写:

int (*arr)[5];

arr = new int[12][5];

Then you can access elements such as arr[11][4] .然后您可以访问诸如arr[11][4]元素。 But not arr[12][5] as you suggest in the question, arrays are zero-indexed and the maximum element index is one less than the dimension.但不是你在问题中建议的arr[12][5] ,数组是零索引的,最大元素索引比维度小一。

All dimensions except the innermost must be known at compile-time.除了最里面的维度之外的所有维度都必须在编译时已知。 If the 5 is actually meant to represent a runtime value then you cannot use C-style arrays for this task .如果5实际上是表示运行时值,那么您不能为此任务使用 C 样式数组。

NB.注意。 Consider using unique_ptr for safe memory management.考虑使用unique_ptr进行安全内存管理。 The code would be auto arr = std::make_unique<int[][5]>(12);代码将是auto arr = std::make_unique<int[][5]>(12); . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM