Topic :Dynamically Memory allocation using New Operator: New Operator | Delete Operator

New Operator:

We use New Operator to allocate Memory for a variable or an object during Run time. When New Operator is used, the variables/objects are considered to the pointers to the memory location allocated to them.

If We want to allocate memory for one single element of a specified data type (it can be a built in data type, structure or class ), we will have to use Operator New in the following form:



//request memory allocation for variable Variable_Name;
Data_type* Variable_Name = new Data_type;
//or
//Request memory allocation for variable name
//and Assign 10 to variable:
Data_type* Variable_Name = new Data_type(10);


Or if we want to allocate Memory for any array, we will have to use this form of New operator:



Data_type* Variable_Name = Data_type int[Size_of_Array];


Let's have an simple example to know how to use New Operator in C++ to allocate Dynamic memory:



/*Simple Example: New Operator: InfoBrother:*/

#include<iostream>
using namespace std;

main()
{
    int* ptr; //pointer to int;
    int num; //to store total number of elements:
    
    cout<<" Enter total Numbers of element to input: "<<endl;
    cout<<" Total Number: ";
    cin>>num;
    
//Dynamic memory allocation having array size num;
    ptr = new int[num];
    
    cout<<" \n Enter your "<< num <<" Elements: "<<endl;
    for(int i=0; i<=num; i++)
    {
        cout<<" Element #: "<<i<<" ";
        cin>>ptr[i];
    }
    
    cout<<"\n\n Your Entered: "<<endl;
    for(int i=0; i<=num; i++)
    {
        cout<<ptr[i]<<" | ";
    }
    
    return 0;
}


To Allocate a Dynamic memory using the New operator, we need a pointer. Because this pointer will allocate a memory and return an address of that memory.



Above we write a simple program to allocate dynamic memory using the New pointer. we declare a pointer to int ptr and this pointer allocate enough memory for integers. the pointer allocates Runtime memory and return the address of that memory: well sometime, might be we face an error while allocation dynamic memory, there could be a lot of reason like our user want a memory greater then we have in our heap so the program will generate an error. so it's better if our program is able to catch the error. so let's back to our program and try to solve this issue.



/*Simple Example: New Operator: InfoBrother:*/

#include<iostream>
using namespace std;

main()
{
    int* ptr; //pointer to int;
    int num; //to store total number of elements:
    
    cout<<" Enter total Numbers of element to input: "<<endl;
    cout<<" Total Number: ";
    cin>>num;
    
//Dynamic memory allocation having array size num;
    ptr = new int[num];
    
if(ptr!=NULL) //Error checker:
{
    cout<<" \n Enter your "<< num <<" Elements: "<<endl;
    for(int i=0; i<=num; i++)
    {
        cout<<" Element #: "<<i<<" ";
        cin>>ptr[i];
    }
    
    cout<<"\n\n Your Entered: "<<endl;
    for(int i=0; i<=num; i++)
    {
        cout<<ptr[i]<<" | ";
    }
}    

else //if Error occur, while allocating memroy:
{
    cout<<" An error occur while allocating memory: "<<endl;
}
    
    
    return 0;
}


Now our above example is pretty Good, if user will request a bunch of memory more then we have, our program will catch it using simple if statement. Now still there is some problem in our code. and may be you notice that, did you? we already discussed in our previous tutorial Introduction to Dynamic Memory that we are responsible to free the allocated Memory once we don't need it more. To Release the memory that was allocated using New operator, C++ Provide another Operator known as delete operator to perform that task.





Delete Operator:

Delete Operator is used to Free the allocated Memory once we don't need it any more. It is Our Responsibility to free the allocated Memory. Its really simple to use delete operator. as shown below:

/*Allocate memory for single element:*/
Data_type* Variable_Name = new Data_type; //Allocate Memory:
delete Variable_Name; //Release memory;

//Allocate memory for Array:
Data_type* Variable_Name = new Data_type[Size_of_Array]; //Allocate Memory:
delete[] Variable_Name; //Release memory;


Let's take one more example here. this is an easy and simple example. this example will allocate enough memory for user to store some data. It's an perfect but easy example for you. you just all need to pay attention to detail.



/*Example: NEW OPERATOR: InfoBrother*/

#include<iostream>
#include<stdlib.h> //exit() function:
using namespace std;

main()
{
    cout<<"\t\t\t MARKS CALCULATOR";
    int no,i,ans; //no= total No of Sunject, i=for Loop.
    
    //*subject=for enter Subject max, sum=for getting Sum.
    float *subject, sum, percentage;

cout<<"\n\n";    
cout<<" Enter Total Number Of Subject: ";
cin>>no;    

subject=new float[no]; //new Operator to Allocate Memory.
if(subject!=NULL) //error chacker.
{ //Main If IN:
    cout<<"\n\n";
cout<<" Enter Subjects Marks: "<<endl;

for(i=0;i<no;i++) //loop for Getting Data:
{
     //As i=0, so if we want to start from 1,
    cout<<"Subject No "<<(i+1)<<" ";
    cin>>subject[i]; //then we need (i+1) = 1.
    sum+=*subject;
    percentage=sum/(100*no)*100;
}
/**********************************************/
//Display Data:

cout<<"\n\n";
cout<<"\t\t Press 1 to Display: "<<endl;
cout<<"\t\t Press 2 to Exit: "<<endl;
cout<<"\n Your Ans= ";
cin>>ans;
cout<<"\n\n";

if(ans==1) //ans Chacker.
{
    cout<<"\t Subject: \t Max: "<<endl;
    cout<<"\n";
    for(i=0;i<no;i++) //Loop To Read and Print Data.
     {
         cout<<"\tSubject No"<<(i+1)<<"\t"<<*subject<<endl;
         subject++;
     }
     cout<<"\t==================";
     cout<<" \n\tThe Sum is: \t"<<sum;
     cout<<" \n\tPercentage is:\t"<<percentage<<" %";
}
else
{
    cout<<"Thank You...!!"<<endl;
    exit(0);
}



} //main IF out:
    
else
{
    cout<<"Sorry...!! Memory Not Allocated"<<endl;
    cout<<" Chack Your Code Again: ";
    exit(0);
}


return 0;
}






I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement