Jraxon
Jraxon

Reputation: 207

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.

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. So I need to be able to do arr[11][4] but not arr[4][11].

I know I can make arr an int** and then assign a 2d array to arr, so please avoid such answer.

I know I can use STL containers such as vector, so please avoid such answer.

Upvotes: 0

Views: 290

Answers (1)

M.M
M.M

Reputation: 141586

You can write:

int (*arr)[5];

arr = new int[12][5];

Then you can access elements such as 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.

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 .

NB. Consider using unique_ptr for safe memory management. The code would be auto arr = std::make_unique<int[][5]>(12);.

Upvotes: 3

Related Questions