Hello friends, in this post today, we learn about What is new and delete operator in c++. so lets start...
new and delete operator |
The technique through which a program can obtain space in the RAM during the execution of the program and not during compilation is called dynamic memory allocation.
data_type *ptr = new data_type;
Here ptr is a variable of data_type. Memory is allocated by finding the size of data_type automatically by the compiler and address of the allocated memory is returned which is stored in ptr.
Some examples:-
int *ptr = new int;
char *ch = new char;
float *fp = new float;
we can assign values to the variable:-
*ptr = 34;
*ch = ‘p’;
*fp = 45.67;
We can also initialize the pointer variable
int *ptr = new int (10);
cout<<*ptr; // prints a
float *fp = new float (34.56);
cout<<*fp; // prints 34.56
The allocated memory can be freed also.
For de-allocation C++ provides delete operator.
The delete operator used to delete memory previously allocated by new operator. For instance if ptr points to memory allocated by new and when this memory is no longer required we can delete it.
Syntax of delete:
delete pointer_variable;
some examples:-
delete ptr;
delete fp;
Example of new and delete operator:-
output:-
I hope that whatever information I have given in this post today, you have liked it and you have understood it.so keep learning and wait for the next post that will help you to increase your knowledge with the something new information.
Thank you so much for reading. And take care about yourself and your family.
Comments
Post a Comment