Dynamic storage allocation in c++ When an object that was created dynamically is destroyed, the delete operator makes sure that the object is cleaned up.

The destructor is first called, and only then is the memory space released. As previously discussed in the section on fundamental types, when you call delete you must ensure that.

the pointer is addressing a dynamic object or that you are dealing with a NULL pointer.

Imagine you are compiling a program that will store an unknown quantity of elements in an array.

Your best option is to let the program create the array dynamically. An array of this type is known as a dynamic array.

#include <iostream>
#include <iomanip>
using namespace std; 
int main(){ 
cout <<"Using a dynamic array.n" << endl;
int size = 0, cnt = 0, step = 10, i;
float x, *pArr = NULL; 
cout <<"Enter some numbers!n" "End with q or another character " << endl; 
while( cin >> x){ 
if( cnt >= size)  // Array too small?
{ // => enlarge it. float *p = new float[size+step];
// Copy the numbers: 
for( i = 0; i < size; ++i) 
p[i] = pArr[i]; 
delete [] pArr;
// Release old array: pArr = p; size += step;
} pArr[cnt++] = x;
} // Work with the numbers: if( cnt == 0)
cout <<"No invalid input!" << endl;
else { 
float sum = 0.0; cout <<"Your input: " <<endl; 
for( i = 0; i <cnt; i++) // To output and
{ // add. cout << setw(10) << pArr[i];
sum += pArr[i]; } 
cout <<"nThe average: " << sum/cnt <<endl; } 
delete [] pArr; // To free the storage return 0;

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Dynamic array in C++

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories


Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page


Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
    Strength indicator
    Log In | Lost Password