C++ Program on Dynamic Memory Allocation
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
// Program for Dynamic Memory allocation using new and delete
#include<iostream>
#define clrscr() system("cls")
using namespace std;
int main()
{
int *ar,n,i,sum=0;
clrscr();
cout<<"\nEnter limit of array";
cin>>n;
ar=new int[n]; //dynamic memory allocation for array
cout<<"\nEnter element in array";
for(i=0;i<n;i++)
cin>>ar[i];
cout<<"------------------------------------\n";
for(i=0;i<n;i++)
{
cout<<ar[i]<<"\n";
sum=sum+ar[i];
}
cout<<"\n Sum of array: "<<sum;
delete ar; //dynamic memory deallocation for array
}Program 2
// Program for Dynamic Memory allocation using new and delete
#include<iostream>
#define clrscr() system("cls")
using namespace std;
class Test
{
int *ar,m,i;
public:
//constructor
Test(int n)
{
cout<<"\nThis is constructor memory allocation done\n";
ar=new int[n];
m=n;
}
void getdata()
{
cout<<"\nEnter element in array";
for(i=0;i<m;i++)
cin>>ar[i];
}
int search(int s)
{
int i;
for(i=0;i<m;i++)
{
if(ar[i]==s)
return 1;
}
return 0;
}
void printdata()
{
cout<<"\n------------------------------------\n";
for(i=0;i<m;i++)
cout<<ar[i]<<"\n";
}
//destructor
~Test()
{
cout<<"\nThis is destructor memory deallocation done\n memory is free now";
delete ar;
}
};
int main()
{
clrscr();
int limit,s;
cout<<"\nEnter limit of array";
cin>>limit;
Test T(limit);
T.getdata();
cout<<"\nEnter element for search";
cin>>s;
if(T.search(s))
cout<<"\nSearching success";
else
cout<<"\nSearching not success";
// T.printdata();
return 0;
}
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

