Dynamic Memory allocation and deallocation in c++ :-
C uses malloc() and calloc() functions to allocate memory dynamically at run time. It uses the function free() to deallocated dynamically allocated memory.
i)C++ supports these functions, it defines two unary operators new and delete that perform the task of allocating and
ii)deallocating the memory in a better and easier way.
A object can be created by using new, and destroyed by using delete.
destroyed by using delete.
new operator:-
new operator can be used to create objects of any type .Hence new operator allocates sufficient memory to hold data of objects and it returns address of the allocated memory. Syntax:
Ex: int *p = new int[10];
ii) delete operator:
If the variable or object is no longer required or needed is destroyed by “delete” operator, there by some amount of memory is released for future purpose. Synatx:
Eg: delete p;
iii)If we want to free a dynamically allocated
array: delete [size] pointer-variable;
Program: write a program to find sum of list of integers
#include<conio.h>
int main()
{
int n,*p;
cout<<"Enter array size:"; cin>>n;
p=new int[n];
cout<<"Enter list of integers"<<endl;
for(int i=0;i<n;i++)
cin>>p[i];
//logic for summation int s=0;
for( int i=0;i<n;i++)
s=s+p[i];
cout<<"Sum of array elements is\n";
cout<<s;
delete [ ]p;
return 0;
}
Enter array size:5 Enter list of integers 1 2 3 4 5
Sum of array elements is 15
Member Dereferencing operator:-
1. Pointer to a member declarator (::*)
3. Pointer to member operator. (.*)
1.Pointer to a member declarator (::*) :-
This operator is used for declaring a pointer to the member of the class
#include<iostream.h>
class sample
{
public:
int x;
};
int main()
{
sample s; //object
int sample ::*p;//pointer decleration
s.*p=10; //correct
cout<<s.*p;
}
Output:
10
2.Pointer to member operator (->*)
class sample
{
public:
int x;
void display()
{
cout<<"x="<<x<<endl;
}
};
int main()
{
sample s; //object
sample *ptr;
int sample::*f=&sample::x;
s.x=10;
ptr=&s;
}
3.Pointer to member operator (.*)
#include<conio.h>
class sample
{
public:
};
int x;
int main()
{
sample s; //object
int sample ::*p;//pointer declaration
s.*p=10; //correct
cout<<s.*p;
}