If your row length is a compile time constant, C++11 allows
auto arr2d = new int [nrows][CONSTANT];
See this answer. Even compilers Compilers like gcc that allow variable-length arrays as an extension to C++ don't allow a 2ndcan use new
as shown here to get fully runtime-variable array dimension that isn't a constantfunctionality like C99 allows, so this isn't a full replacement for what you can do in Cbut 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 better optimization especially when the same compiler needs to checkoptimizations as a real 2D array (e.g. proving or provechecking 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.