What is the use of new and delete operator in C++?

new operator is used to dynamically allocate memory on the heap. Memory allocated by new must be deallocated using delete operator.

Syntax of new is:
p_var = new type name;
where p_var is a previously declared pointer of type typename. typename can be any basic data type.

new can also create an array:
p_var = new type [size];
In this case, size specifies the length of one-dimensional array to create.

Example 1:

int  *p;

p=new int;

It allocates memory space for an integer variable. And allocated memory can be released using following statement,

delete p;

Example 2:

int *a;

a = new int[100];

It creates a memory space for an array of 100 integers. a[0] will refer to the first element, a[1] to the second element, and so on. And to release the memory following statement can be used,

delete []a;


2 thoughts on “What is the use of new and delete operator in C++?

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.