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
Tand are going to allocate an array of sizeNthen this expressionreturns the address of the type
T *of the first element of the allocated array.So you should write
For example if
Tis 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]whereMis a constant integer expression.You can write
or
and
So you allocated an array of
Nelements where each element has sizesizeof( int[M]and the pointerapoints to the first element of the array.Because
Tis equivalent tpint [M]you can writethat is this statement allocates an array of
Nelements of the typeint[M]and the pointeragets 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
relements (objects) of typeint[c]andais pointer to the first element of the allocated array.