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.
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.
I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:
There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).
Compile time dimensions
Use a
std::array
ofstd::array
and then usenew
to put it on the heap:Again, this only works if the sizes of the dimensions are known at compile time.
Run time dimensions
The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload
operator []
to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:
So we create an array with
std::make_unique<int[]>(rows * columns)
entries. We overloadoperator []
which will index the row for us. It returns anint *
which points to the beginning of the row, which can then be dereferenced as normal for the column. Note thatmake_unique
first ships in C++14 but you can polyfill it in C++11 if necessary.It's also common for these types of structures to overload
operator()
as well:Technically I haven't used
new
here, but it's trivial to move fromstd::unique_ptr<int[]>
toint *
and usenew
/delete
.In C++11 it is possible:
This way, the memory is not initialized. To initialize it do this instead:
Sample program (compile with "g++ -std=c++11"):
Output:
I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].
The key is the parentheses in the array declaration.
I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:
Try doing this: