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.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
If your row length is a compile time constant, C++11 allows
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:
The above, for
colCount= 5
androwCount = 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.