Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a 2d array in C++ using new?

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.

like image 886
user20844 Avatar asked Jun 01 '09 20:06

user20844


People also ask

How do you initialize a new 2D array?

Here is how we can initialize a 2-dimensional array in Java. int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.

How do you create an array in New?

Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.


1 Answers

If your row length is a compile time constant, C++11 allows

auto arr2d = new int [nrows][CONSTANT]; 

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:

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:

enter image description here

Don't forget to delete each row separately with a loop, before deleting the array of pointers. Example in another answer.

like image 102
mmx Avatar answered Sep 30 '22 17:09

mmx