Sunday 26 July 2015

  • Sunday, July 26, 2015
C++ new operator example: C++ code using new operator to dynamically allocate memory on heap.

C++ programming code

#include <iostream>
 
using namespace std;
 
int main()
{
   int n, *pointer, c;
 
   cout << "Enter an integer\n";
   cin >> n;
 
   pointer = new int[n];
 
   cout << "Enter " << n << " integers\n";
 
   for ( c = 0 ; c < n ; c++ )
      cin >> pointer[c];
 
   cout << "Elements entered by you are\n";
 
   for ( c = 0 ; c < n ; c++ )
      cout << pointer[c] << endl;
 
   delete[] pointer;
 
   return 0;
}
If you allocate memory using new then it will remain allocated until the program exits unless you explicitly deallocate with delete. Above program contains only one function so memory will be deallocated after program exits but we have specifically used delete as it is a good programming practice to deallocate memory which is not required further in the program.
Related Posts Plugin for WordPress, Blogger...

Vacancy

RBI has announced the recruitment for 134 GRADE B OFFICERS.
 The examination will be in two phases.
 The detailed advertisement will be published on 5th October.

Popular Posts