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, *p, c;
   cout << "Input an integer\n";
   cin >> n;
   p = new int[n];
   cout << "Input " << n << " integers\n";
   for (c = 0; c < n; c++)
      cin >> p[c];
   cout << "The integers are:\n";
   for (c = 0; c < n; c++)
      cout << p[c] << endl;
   delete[] p;
   return 0;

Output of the program:

Input an integer
Input 2 integers
The integers are:

If you allocate memory using new, it remains allocated until the program exits unless you explicitly deallocate with delete. The program contains only one function so memory will be deallocated after program exits, but we have used delete as it's a good programming practice to deallocate memory that isn't required further in the program.