You are here

C++ new operator example

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 << "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
Input 2 integers
Elements entered by you are

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.