You are here

C++ new operator example

C++ new operator example: C++ code using new operator to allocate memory on heap dynamically.

C++ programming code

#include <iostream>
 
using namespace std;
 
int main()
{
   int n, *pointer, c;
 
   cout << "Input an integer\n";
   cin >> n;
 
   pointer = new int[n];
 
   cout << "Input " << 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;
}

Output of program:

Input an integer
2
Input 2 integers
456
-98
Elements entered by you are
456
-98

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 used delete as it is a good programming practice to deallocate memory which isn't required further in the program.