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.
Start by defining the array using pointers (Line 1):
This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory? Today I finally found the answer. Using the following code, you can do just that:
When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:
As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.
This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.
I hope this code will help you as much as it helped me.
This is not the one in much details, but quite simplified.
Remember:
1. ONLY THE THE FIRST INDEX CAN BE A RUNTIME VARIABLE. OTHER INDEXES NEED TO BE CONSTANT
2. NO INDEX CAN BE LEFT EMPTY.
As mentioned in other answers, call
to deallocate memory associated with the array when you are done with the array.
Why not use STL:vector? So easy, and you don't need to delete the vector.
Source: How to Create 2, 3 (or Multi) Dimensional Arrays in C/C++?
A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.
Here N is row and M is column.
dynamic allocation
fill
print
free
This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.
When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library,
multi_array
. It even includes amulti_array_ref
class that can be used to wrap your own one-dimensional array buffer.