B.TECH CSE BT ECE(oop's): Dynamic memory allocation
But if we need to allocate memory at runtime me must use new operator followed by data type. If we need to allocate memory for more than one element, we must provide total number of elements required in square bracket[ ]. It will return the address of first byte of memory.
Syntax of new operator
ptr = new data-type;
//allocte memory for one element
ptr = new data-type [ size ];
//allocte memory for fixed number of element
C++ delete operator
Syntax of delete operator
delete ptr;
//deallocte memory for one element
delete[] ptr;
//deallocte memory for array
For Example
#include<iostream.h>
#include<conio.h>
void main()
{
int size,i;
int *ptr;
cout<<"\n\tEnter size of Array : ";
cin>>size;
ptr = new int[size];
//Creating memory at run-time and return first byte of address to ptr.
for(i=0;i<5;i++) //Input arrray from user.
{
cout<<"\nEnter any number : ";
cin>>ptr[i];
}
for(i=0;i<5;i++) //Output arrray to console.
cout<<ptr[i]<<", ";
delete[] ptr;
//deallocating all the memory created by new operator
}
Comments
Post a Comment