How to create a dynamic array of integers in C++ using the new keyword


In C++, a dynamic array can be created using new keyword and can be deleted it by using delete keyword.

Let us consider a simple example of it.

Example Code

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int i,n;
   cout<<"Enter total number of elements:"<<"\n";
   cin>>n;
   int *a = new int(n);
   cout<<"Enter "<<n<<" elements"<<endl;
   for(i = 0;i<n;i++) {
      cin>>a[i];
   }
   cout<<"Entered elements are: ";
   for(i = 0;i<n;i++) {
      cout<<a[i]<<" ";
   }
   cout<<endl;
   delete (a);
   return 0;
}

Output

Enter total number of elements:7
Enter 7 elements
1 2 3 4 5 6 7
Entered elements are: 1 2 3 4 5 6 7

In this program, memory is allocated by declaring, int *a=new int(n), using new keyword. The occupied memory can be retrieved by calling delete (a).

Updated on: 30-Jul-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements