Method:3
To create an array of a specified size and transfer the base address to the pointer variable
(i)
int *a=new int[5];
(ii)
float *p=new float[10];
(iii)
char *c=new char[20];
Note:
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 “;
cin>>n;
int *a=new int[n];
if(a==NULL)
{
cout<<”memory allocation failed”<<endl;
return;
}
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
Allocation |
Deallocation |
int *a=new int; |
delete a; |
int *a=new int(10); |
delete a; |
int *a=new int[20]; |
delete []a; |