new and delete operator

new operator:-

In dynamic memory allocation new operator is used to allocate memory at run time. It will return the address of first byte of allocated memory to a pointer variable.
डायनामिक मेमोरी एलोकेशन में new ऑपरेटर का प्रयोग रन टाइम पर मेमोरी प्रदान करने के लिए किया जाता है। यह प्रदत्त मेमोरी की प्रथम बाइट का एड्रेस पॉइंटर वेरिएबल को प्रदान करता है।
Syntax-
ptr = new data-type;
//allocate memory for one element

ptr = new data-type[size];
//allocate memory for fixed number of elements

delete operator:-

In dynamic memory allocation delete operator is used to deallocate memory which is created by new operator at run time. Once the memory is no longer needed it should be freed by program so that it will be available for other request. It will accept a pointer variable to deallocate memory and add it to free memory pool (heap).
डायनामिक मेमोरी एलोकेशन में delete ऑपरेटर का प्रयोग new ऑपरेटर द्वारा रन टाइम पर प्रदत्त मेमोरी को पुनः वापस लेने के लिए किया जाता है। एक बार प्रदत्त मेमोरी की आवश्यकता समाप्त हो जाने के बाद, प्रोग्राम द्वारा उसे फ्री किया जाता है जिससे उस मेमोरी का प्रयोग दुसरे प्रोग्रामस द्वारा किया जा सके। यह पॉइंटर वेरिएबल की सहायता से प्रदत्त मेमोरी को वापस करता है एवं फ्री मेमोरी पूल (हीप) में जोड़ता है।
     
Syntax:-
delete ptr;
//deallocte memory for one element

delete[] ptr;
//deallocte memory for array

Example 1:-
#include<iostream.h>
#include<conio.h>
void main() {
int *ptr;
ptr = new int;
cout<<"Enter a number\n";
cin>>ptr;
cout<<"Number is="<<*ptr;
delete ptr;
getch();
}

Example 2:-
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
class m{
public:
int m;
m(){m=5;}
};
void main(){
m *ptr;
clrscr();
ptr=new m;
cout<<ptr->m;
delete ptr;
getch();
}

No comments:

Post a Comment