Need help with dynamic allocation of memory for 2D arrays in C ++

advertisements

I had been trying to allocate dynamic memory for a two-dimensional array. After searchin a lot I've found a code that looks easier than others still I'm unable to understand each and every detail of it. Can someone explain me how does the following code assigns memory to the array dynamically. Really looking forward for help and sorry but I'm new to C++ and want to learn it.

void main()
{
int m,n;
cin>>m;
cin>>n;
//Allocate
int *a = new int[m*n];
//Use a[m][n]
for( int i = 0 ; i < m ; i++)
        for ( int j = 0 ; j < n ; j++)
                 a[i*n + j] = 1;
}


First of all, what you're doing, is adding 1 to different slots of a ONE-dimensional array.

Here's a commented version of your code:

int *a = new int[m*n];  // declares a pointer a, that points to a newly
                        // allocated space on the heap, for an array of size m*n.

for( int i = 0 ; i < m ; i++)        // loop through m number of times
    for ( int j = 0 ; j < n ; j++)   // loop through n number of times PER m
             a[i*n + j] = 1;         // assigns 1 to a spot [i*n + j]

THIS is how you make a dynamic 2D array (in other words, array of pointers to arrays):

const int sizeX = 10;
const int sizeY = 5;

int** arrayOfPointers = new int*[sizeX];
for(int i = 0; i < sizeX; i++)
    arrayOfPointers[i] = new int[sizeY];

Then, you can add multiple elements to that array using a double loop (NOT TESTED):

for(int i = 0 ; i < sizeY ; i++)        // loop through all the rows
    for (int j = 0 ; j < sizeX ; j++)   // loop through all columns for row i
         arrayOfPointers[i][j] = i*j; // assigns i*j to a spot at row i, column j

This is how you can print out the contents of the 2D array:

for(int i = 0 ; i < sizeY ; i++) { 

    for (int j = 0 ; j < sizeX ; j++)
         cout << arrayOfPointers[i][j];

    cout << endl; // go to the next line when the row is finished

}