C++:Pointers-new and delete operators

To create an array of a specified size and transfer the base address to the pointer variable

int *a=new int[5];

float *p=new float[10];

char *c=new char[20];

Before using the memory block which is allocated dynamically using “new” operator it is important to verify whether the memory is successfully allocated or not. If memory is successfully allocated then base address of the allocated memory block is returned back and stored in the pointer variable. On the other hand if memory allocation fails then NULL is returned back and stored in the pointer variable.

int n;
cout<<”enter total elements “;
int *a=new int[n];
cout<<”memory allocation failed”<<endl;

delete operator

When memory is no longer required, then it needs to be deallocated so that the memory can be used for another purpose. This can be achieved by using the delete operator.

“delete” operator helps us to release the memory block which has been allocated dynamically using the “new” operator.
The function of the delete operator is the same as that of the free() function used in the “C” language.
The “delete” operator calls upon the function operator “delete()” to release the memory.

Allocation Deallocation of memory



int *a=new int;

delete a;

int *a=new int(10);

delete a;

int *a=new int[20];

delete []a;