How to declare a two-dimensional dynamic array in C++ using the new operator?
Hi! I just started learning C++ and ran into a problem. I need to create a two-dimensional array whose size will only be known at runtime. I know how to declare a static two-dimensional array: `int arr[3][4];`, but when I try to make the sizes variable, the compiler complains.
I tried this code:
```cpp
int rows = 5, cols = 10;
int arr[rows][cols]; // Error! Needs a compile-time constant
```
I read about dynamic memory and realized I need to use `new`. But how do I properly allocate memory for a two-dimensional array? I saw several options online, but they are all different. Some use an array of pointers, others allocate one large block of memory.
Please write the correct and reliable way to create a two-dimensional array using `new`.
No answers yet.
Log in to leave an answer