Introduction
In this article I am going to demonstrate the dynamic allocation and de-allocation of a two dimensional array using pointers.One of the great features of C++ is the memory management,it enables us to allocate the memory and clean it up when we finish using it. While in the languages that compiles to an intermediate language like Java and C# , the garbage collect is not leaved to the developer it is done automatically when the object allocated in the memory is not in use. But this is done by the operating system and may leave some allocated memory for a while.
The Code
Prepare the main.cpp file by including iostream library and using the namespace std
#include <iostream>
using namespace std;
void main(void)
{
}
In function main() declare an int variable to store the size of the array and declare a pointer to a pointer to a float (it may be a little bit confusing ...but imagine u declared a pointer to a float then you decalred a pointer to point to that pointer ... ).
int size = 7000;
float** MainArray = NULL;
MainArray = new float*[size];
cout <<"Allocating..."<<endl;
for(int i = 0 ; i < size ; i++)
{
float* SubArray = NULL;
SubArray = new float[size];
for(int j = 0 ; j < size ; j++)
{
SubArray[j] = (float)j;
}
MainArray[i] = SubArray;
}
The variable MainArray supposed to point to the SubArray and the SubArray supposed to point to a float values hence we get a two dimensional array.
After we allocated the array (the developer may do some operations on it or use it for storing data etc.. ) we are now concerned with de-allocate it and this is done using the key word delete and provide it with a pointer to delete it then assign it to NULL like in the next code block.
int key = 1 ;
cout << "Press 0 then Enter to clean up the memory" << endl;
cin >> key ;
if(key == 0)
{
for(int i = 0 ; i < size ; i++)
{
delete[] MainArray[i];
MainArray[i] = NULL;
}
delete[] MainArray;
MainArray = NULL;
cout << "Memory cleared" << endl;
}
system("PAUSE");
The loop iterates throw the main array and delete every pointer to a float then after finshing the main array pointer is deleted.
You can see the effect of the clean up by opening the Process tab in the task manager and notice the memory usage of MemoryCleanUp.exe before and after hitting 0 and Enter do de-allocate the array,thats it ..very simple