Wednesday, July 3, 2013

Dynamic Memory Allocation For Arrays in C++

!Hola,

This post describes the way to make dynamic allocation for arrays in C++. Sounds interesting ?
For beginners this might be little bit confusing. So, specially for them let me take an example from JAVA. Can you recall how a 1-D array is created in java?

int x[ ] = new int [3];

make sense ? OK !!! so what is the role of "new" here?

new operator allocates memory for three integer elements of array x. Now if you go to Arrays topic of any JAVA book you will find the way to make dynamic array. Now for instance check the 2D array below.

int x[ ][ ] = new int[4][ ];
x[0] = new int[1];
x[1] = new int[2];
x[2] = new int[3];
x[3] = new int[4];

will allocate memory for this array like this:



Make sense !!!!!

I guess you might have got an idea what does dynamic array means. Cool !!!
Now the question is how you will do this in C++ ?
The solution for this is pointers.

We will make use of pointers to dynamically declare and initialize arrays just like we did above with JAVA. The code snippet below will explain everything.



syntax to dynamically create 2-D array:

Object **array;
array = new Object* [rowsize];

for(int i = 0; i < rowsize; i++)
array[i] = new Object[columnsize];

 

example of 1-D array:

int* x = new int[2];
x[0] = 1;
x[1] = 2;

example of 2-D array: ( check this, its similar to what we did above with JAVA )

    int ** a = new int*[2];
    a[0] = new int[2];
    a[0][0] = 1;
    a[0][1] = 2;
    a[1] = new int[3];
    a[1][0] = 3;
    a[1][1] = 4;
    a[1][2] = 5;
   

example of 3-D array:

    int *** b = new int**[2];
    b[0] = new int*[2];
    b[0][0] = new int[2];
    b[0][1] = new int[2];
    b[0][0][0] = 1;
    b[0][0][1] = 2;
    b[0][1][0] = 3;
    b[0][1][1] = 4;
   
    b[1] = new int*[2];
    b[1][0] = new int[2];
    b[1][1] = new int[2];

    b[1][0][0] = 5;
    b[1][0][1] = 6;
    b[1][1][0] = 7;
    b[1][1][1] = 8;

Hope it was useful !!