new keyword in C++

New Operator in C++

In case of static memory allocation once the memory is allocated it cannot be deleted and unused memory gets wasted whereas dynamic memory allocation  enables the programmer to manually create and delete (give back to store) the memory at any point of time

Dynamic Memory Allocation: The advantage of dynamic memory mechanism used to locate memory at the time of execution without any wastage of memory block

In C++ dynamic memory concept is supported by new and delete operators, here  we will discuss the new operator in detail

New: The new operator allocates the required bytes of memory by returning a pointer to the  allocated memory

Syntax

datatype *varname=new datatype[size]

Example

int *p =new int[7] //14 bytes= 7 *2 bytes
New Operator in C++
  • For example, if the size of the integer is 2, 14 bytes of memory is returned by the new operator for n specified as 7
  • initially pointer variable p contents of base address i.e  first byte of memory

C++ program to create memory dynamically to  store some data and display the data

#include<iostream>
using namespace std;

main()
{

int *p ,i,n;
cout<<"enter the size:";
cin>>n;

p=new int[n];//allocates  n*sizeof(int)  bytes

if(p==NULL)//in rare case if available memory not available 
{
cout<<"\nmemory alloacation failed";
exit(1);
}

cout<<"\nenter the elements\n";
for(int i=0;i<n;i++)
{
cin>>*(p+i);
}

cout<<"elements are:\n";
for(int i=0;i<n;i++)
{
cout<<*(p+i)<<"\t";
}

}

Output

Enter the size 
5 
Enter the elements
1 6 0 8 3
Elements are:
1 6 0 8 3

Heap memory

Dynamic memory allocation always takes place in a memory area called heap, because heap Data Structure has a property to grow and shrink at any point of time i.e memory can be deleted and allocated at any point of time as per the requirement