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.
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;
pointer_variable = new datatype;
Here is the syntax to initialize the memory,
pointer_variable = new datatype(value);
pointer_variable = new datatype(value);
Here is the syntax to allocate a block of memory,
pointer_variable = new datatype[size];
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