Pointer , New and Delete in C++
A pointer is a variable that contains address of another variable. The declaration of a pointer variable takes following form:
Data_type refer to any predefined data types and indicates the type of the variable that the pointer points to. The (*) asterisk indicates that the variable pointer_name is a pointer variable to type Data_type.
It declares the variable ‘p’ as a pointer variable that points to an integer data type.
New and delete
When amount of memory is predefined and the memory is allocated during compile time, it is referred to as static memory allocation.
When amount of memory to be allocated is not preknown and the memory is allocated during runtime as and when required, it is referred to as dynamic memory allocation.
In C++, dynamic allocation is facilitated through new and delete operator. Hence, these two unary operators new and delete performs the task of allocating and freeing memory during runtime.
The operator new allocates memory for the specified data type from the free store.
The general syntax of new operator is:-
Data_type pointer_variable = new Data_type;
int *ptr = new int;
The operator new can also allocate memory from array. To allocate memory for a one dimensional array, new may be used in the following form:
Data_type pointer_variable = new Data_type [size];
Where size is the number of elements in the array.
int * marks = new int ;
The new operator reserves many chunk of memory. If not needed, the memory reserved should be released for reuse. This deallocation of memory is done by operator called as delete operator.
To ensure effective use of memory, delete operator is used which releases the heap memory space allocated by the new operator.
The general syntax of delete operator is:-
Int *ptr= new int;
Delete ptr; // delete or release memory space
The general syntax of the delete operator for an array data type is:-
Delete  pointer_variable;
Int *marks = int ;
Delete  marks;
A program to create two arrays to store roll number and marks of some students, whose number would be known at runtime using new and delete operators.
Void main ()
Int *rollno; // int pointer for roll no array
Float *marks; // float pointer for marks array
Cout<<”\n How many number?”;
rollno=new int [size];
marks= new float [size];
For (i=0; i<size; i++)
cout<<”\n Enter roll no and marks for the student”;
cout<<”\n Roll No \t marks”;
For (i=0; i<size; i++)
delete  rollno;
delete  marks;
- Arrays In C++ Arrays in C++ Array is a collection of similar type...
- Predefined Data Types Predefined data types Data can be of many types (e.g....
- Type Conversion In C++ Type Conversion In C++ This process of converting one predefined...
- Passing Arrays To Functions Passing arrays to functions Array can be passed as argument...
- C++ Cast Explicit type conversion (casts) in c++ or c++ cast It...