Reputation: 295
I had a question in my assignment where i used the following way to define a 2D array:
// Allocating two two-dimensional matrix
int** matrix1 = new int*[rows];
for( int i=0; i!=rows; ++i )
matrix1[i] = new int[cols];
int** matrix2 = new int*[rows];
for( int i=0; i!=rows; ++i )
matrix2[i] = new int[cols];
I found it really hard to understand this method and even after completing the course, i find this too confusing. I managed during the semester by finding a simpler way on the internet but i would really love to know exactly what is happening here.
Can someone please explain it in as simple words as possible? Thanks!
Upvotes: 1
Views: 186
Reputation: 23624
dynamic 2D array is basically an array of pointers, syntax wise, it is:
int** matrix1; //for integer 2D array
matrix1
is an array of pointers
that points to int. int arrays are decayed to int*
. Therefore, you have the above syntax. To better understand it, think about how you deal with dynamic 1D arrays as follows:
int* A = new int[SIZE_OF_ARRAY];
here, A
is of type int*
, it is functionally similar to static array A[SIZE_OF_ARRAY]
if SIZE_OF_ARRAY
is a compile time constant. Now assuming you have another static array B[ROWS][COLS]
, with ROWS
and COLS
compile time constants, however, if these array size values are not constants at compile time, you need to allocate memory dynamically, so for B
, you have to do the same thing as you did for matrix1
:
int **B;
To allocate memory, you have to first allocate how many pointers the array of pointers store
, meanwhile, you also need to allocate memory for how many int elements each pointer points to
, so you need the nested for loops for this purpose.
In C++, it is better to use vector<vector<int>>
to replace int** matrix1
.
You may view a memory layout of 2D arrays here: http://www.fredosaurus.com/notes-cpp/arrayptr/23two-dim-array-memory-layout.html
Upvotes: 1
Reputation: 46051
I think this image explains rather good how it's put together. array
being one of your matrix.
matrix1
points to an array of pointers (rows), where each pointer points to an array of ints (columns).
Upvotes: 2