Can someone please help me understand the last line in this snippet of code? I don't understand how that dynamically allocates the 2D array. I understand that on line 6, it's creating a pointer named 'a' and pointing it to an array of integers of size 5 as defined by 'c'.
What I don't understand is how that "new int" statement works with the r thrown into the equation. Thanks in advance.
#include <iostream>
const int c = 5; //num of columns
int main () {
int r = 5;
int (*a)[c];
a = new int[r][c]; // allocate array
}
If you have a type
T
and are going to allocate an array of sizeN
then this expressionreturns the address of the type
T *
of the first element of the allocated array.So you should write
For example if
T
is equivalent to the type intor
then the above allocation can be written
the size of element of the array is equal to
sizeof( int )
and usually is 4 bytes.Now let's assume that you are going to allocate an array of elements of type
int[M]
whereM
is a constant integer expression.You can write
or
and
So you allocated an array of
N
elements where each element has sizesizeof( int[M]
and the pointera
points to the first element of the array.Because
T
is equivalent tpint [M]
you can writethat is this statement allocates an array of
N
elements of the typeint[M]
and the pointera
gets the address of the first element of the allocated array.Returning to your program example
int r = 5 int (*a)[c]; a = new int[r][c];
you can rewrite it the following way
or
and
that is this statements allocates an array of
r
elements (objects) of typeint[c]
anda
is pointer to the first element of the allocated array.