C++ new & delete Operator


C++ new operator

Dynamic memory allocation means creating memory at runtime. For example, when we declare an array, we must provide size of array in our source code to allocate memory at compile time.

But if we need to allocate memory at runtime me must use new operator followed by data type. If we need to allocate memory for more than one element, we must provide total number of elements required in square bracket[ ]. It will return the address of first byte of memory.

Syntax of new operator

            ptr = new data-type;
            //allocte memory for one element

            ptr = new data-type [ size ];
            //allocte memory for fixed number of element

C++ delete operator

Delete operator is used to deallocate the memory created by new operator at run-time. Once the memory is no longer needed it should by freed so that the memory becomes available again for other request of dynamic memory.

Syntax of delete operator

            delete ptr;
            //deallocte memory for one element

            delete[] ptr;
            //deallocte memory for array


Example of c++ new and delete operator


	void main()

		int size,i;
		int *ptr;

		cout<<"\n\tEnter size of Array : ";

		ptr = new int[size];
		//Creating memory at run-time and return first byte of address to ptr.

	  for(i=0;i<5;i++)        //Input arrray from user.
		 cout<<"\nEnter any number : ";

	  for(i=0;i<5;i++)         //Output arrray to console.
	  cout<<ptr[i]<<", ";

	  delete[] ptr;
	  //deallocating all the memory created by new operator


	Output :

			Enter size of Array : 5

			Enter any number : 78
			Enter any number : 45
			Enter any number : 12
			Enter any number : 89
			Enter any number : 56

			78, 45, 12, 89, 56,