C++:Pointers|new operator

new Operator

new operator helps us to allocate memory dynamically for an object of a specified size. The function of new operator is the same as that of malloc(), calloc() functions used in “C” language.
The new operator calls upon the function operator “new()” to allocate the memory.

When an expression of new statement is executed the following process takes place.

• Memory of specified size is allocated dynamically
• If required the allocated memory location is initialized
• The base address of the allocated memory is returned back and stored in the pointer variable.

Syntax:

(a). Datatype *pointervariable=new datatype;

(b). Datatype *pointervariable=new datatype (value);

( c).Datatype *pointervariable=new datatype [size];

Method:1
To create a memory equal to the size of data type and transfer the base address to the pointer variable

(1).
int *a=new int;
or
int *a;
a=new int;

(ii).
float *b=new float;
or
float *b;
b=new float;

(iii).
char *n=new char;
or
char *n;
n=new char;

Method:2
To create a memory equal to the size of data type, initialize the memory location and transfer the base address to the pointer variable

(i)
int *a=new int(10);

(ii)
char *c=new char(‘A’);

(iii)
float *d=new float(10.98);