Pages

Sunday 19 September 2021

new and delete operators in c++

new operator:
The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address.

Here is the syntax of new operator in C++ language,
pointer_variable = new datatype;

Here is the syntax to initialize the memory,
pointer_variable = new datatype(value);

Here is the syntax to allocate a block of memory,
pointer_variable = new datatype[size];

#include<iostream.h>
#include<conio.h>
void main()
{
 int *x;
 float *y;
 char *z;
 clrscr();
 x = new int(10);
 cout<<&x<<ends<<*x<<endl;
 y = new float(1.5);
 cout<<&y<<ends<<*y<<endl;
 z = new char('k');
 cout<<&z<<ends<<*z<<endl;
getch();
}

output:

//Program to illustrate one dimensional array using new and delete operators
#include<iostream.h>
#include<conio.h>
void main()
{
 int n;
 clrscr();
 cout<<"enter array size:";
 cin>>n;
 int *p = new int[n];
 for(int i=0;i<n;i++)
  {
    cin>>p[i];// cin=[p+i]
  } 
 cout<<"elements are:";
 for(i=0;i<n;i++)
  {
  cout<<ends<<p[i];  //cout=*[p+i]
  }
delete p;
getch();
}


No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...