DATA STRUCTURES

  • Home
  • DATA STRUCTURES USING C++


Admission Enquiry Form

What is Dynamic Memory allocation?

The allocation of the memory at runtime is known as dynamic memory allocation. It is different from static memory allocation because memory is allocated at compile time in the case of static memory allocation.

Operator to allocate dynamic memory in C++

  1. new
  2. delete



new Operator in C++

Allocating memory to integer variable in C++ using new operator.

Syntax of malloc() function:

pointerVariable = new dataType;

Example

ptr = new int;

Use of new operator to allocate memory for one integer value

#include<iostream>
using namespace std;
int main()
{
int *ptr;
ptr=new int;
cout<<"Enter number ";
cin>>*ptr;
cout<<"Value is "<<*ptr;
}



Use of new operator to allocate memory for array elements

//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)<<endl;
}
return 0;
}




Use of new operator to allocate memory for structures

//dynamic memory to structure
#include<iostream>
using namespace std;
struct student
{
char name[10];
int rollno;
float fee;
};
int main()
{
student *sptr;
sptr=new student;
system("cls");
cout<<"Enter name of the student ";
cin>>sptr->name;
cout<<"Enter rollno of the student ";
cin>>sptr->rollno;
cout<<"Enter fee of the student ";
cin>>sptr->fee;

cout<<endl<<"Value of the structure are: "<<endl;
cout<<"Name is : "<<sptr->name;
cout<<endl<<"Rollno is :"<<sptr->rollno;
cout<<endl<<"Fee is :"<<sptr->fee;
system("pause");
return 0;
}




Dynamic Memory to a class:

Use of delete operator

A delete operator is used to deallocate memory space that is dynamically created using the new operator.

//dynamic memory to a class
#include<iostream>
using namespace std;
class Test
{
int num1,num2;
public:
void input()
{
cout<<"Enter first number ";
cin>>num1;
cout<<"Enter second number ";
cin>>num2;
}
void display()
{
cout<<"num1= "<<num1;
cout<<endl<<"num2= "<<num2;
}
};//end of class

int main()
{
Test *ptr;
ptr=new Test();//dynamic memory to class
ptr->input();
ptr->display();
delete ptr;//release the memory on free store
}