C++ dynamic arrays

To create a dynamic array in C++, you will need to use new and delete operators. These two operators help you to dynamically allocate and deallocate the memory efficiently. In the example code below, at first we allocate space for an array of 5 elements. Then the size of the array increases one by one if it reaches the original size limit.

#include <iostream>
#include <conio.h>
using namespace std;

int *expand(int *arr,int n){
   int *temp=new int[n+1]; //extend for addinal 1 item
   for(int i=0;i<n;i++)
      temp[i]=arr[i]; //copy from old to new array
   return temp; //return the new array
int main(){
   int *dataset=new int[5];//allowcate array for 5 element
   int *temp;
   int val,i=0;
   while(cin>>val) { //press any alphabetical character to exit
             if(i>4) {
                   temp=dataset; //let temp take the old array
                   dataset=expand(dataset,i); //update array size
                   delete temp; //delete the temp
  //print array five elements per line
  cout<<"Values you entered:\n";
   for(int j=0;j<i;j++){
     if(j%5==0 && j!=0) cout<<"\n";

   delete dataset; //release memory space used by array
   return 0;

Posted by: Dara | post date: 01-27-2013 | Subject: C++ Programming Language

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.