Dynamic Memory Allocation in C++: (new operator)
What is Dynamic Memory in C++
In C++ we can allocate static memory or Dynamic memory to the variables as well as objects in C++
Dynamic memory allocation is also known as free store memory allocation or heap memory allocation
We can allocate dynamic memory or memory at run time by using new operator in C++
Code for allocating memory to int
Code for allocating memory to int
//dynamic memory allocation in CPP
#include<iostream>
using namespace std;
int main()
{
int *ptr;
ptr=new int;//new is used to allocation dynamic memory
*ptr=10;
cout<<*ptr;
}//end of main
Code for allocating dynamic memory to an Array
Code for allocating dynamic memory to an Array
//Dynamic memory allocation in C++ to integer array.
#include<iostream>
using namespace std;
int main()
{
int *ptr;
int i;
ptr=new int[5];//dynamic memory allocation
for(i=0;i<5;i++)
{
cout<<endl<<"Enter a value: ";
cin>>*(ptr+i);
}//end of loop
cout<<endl<<"Values of the array are: "<<endl;
for(i=0;i<5;i++)
{
cout<<*(ptr+i)<<" ";
}
return 0;
}//end of main
Output:
Enter a value: 10
Enter a value: 20
Enter a value: 30
Enter a value: 40
Enter a value: 50
Values of the array are:
10 20 30 40 50
Code for allocating dynamic memory to a Structure
Code for allocating dynamic memory to a Structure
//Dynamic memory allocation in C++ to Structure
#include<iostream>
using namespace std;
struct student
{
char name[10];
int rollno;
float fee;
};
int main()
{
student *sptr;
sptr=new student;
cout<<"Enter the name of the student: ";
cin>>sptr->name;
cout<<"Enter the rollno of the student: ";
cin>>sptr->rollno;
cout<<"Enter the fee of the student: ";
cin>>sptr->fee;
cout<<endl<<"values of the structure are: "<<endl;
cout<<"Name is : "<<sptr->name<<endl;
cout<<"Rollno is : "<<sptr->rollno<<endl;
cout<<"Fee is : "<<sptr->fee<<endl;
return 0;
}//end of main
Output:
Enter the name of the student: nandini
Enter the rollno of the student: 1
Enter the fee of the student: 10000
values of the structure are:
Name is : nandini
Rollno is : 1
Fee is : 10000
Code for allocating memory to an Object
//Dynamic memory allocation to object
#include<iostream>
using namespace std;
class Demo
{
public:
int ctr;
Demo()//default constructor
{
ctr=0;
}
void setData(int n1)
{
ctr=n1;
}
void showData()
{
cout<<endl<<"ctr="<<ctr;
}
};//end of class
int main()
{
Demo *dptr;//creating pointer of Demo class
dptr=new Demo;//allocating memory on free store
dptr->setData(100);
dptr->showData();
delete dptr;//deallocating memory from free store
} //end of main