Wednesday, August 7, 2013

Array Dynamically

2- D array creation dynamically

A dynamic 2D array is basically an array of pointers to arrays. You should initialize it using a loop:
In CPP

// in CPP 

int** ary = new int*[Rows];
for(int i = 0; i < Rows; ++i)
    ary[i] = new int[Rows]; 

and then clean up would be: 

for(int i = 0; i < sizeY; ++i)  { 
    delete [] ary[i]; } 
 delete [] ary;

in  C
 
 
double** Make2DDoubleArray(int arraySizeX, int arraySizeY) {
double** theArray;
theArray = (double**) malloc(arraySizeX*sizeof(double*));
for (int i = 0; i < arraySizeX; i++)
   theArray[i] = (double*) malloc(arraySizeY*sizeof(double));
   return theArray;
} 

Then, inside the code, i would use something like
double** myArray = Make2DDoubleArray(nx, ny);
Voila!

Of course, do not forget to remove your arrays from memory once you're done using them. To do this

for (i = 0; i < nx; i++){
   free(myArray[i]);
}
free(myArray);