previous | start | next

18. New and Dynamic Arrays

The new operator also has a version that can allocate an array of elements. The address of the first of these elements is the value returned by this version of new.

Example: Create an array of 100 doubles and store the beginning address in a pointer, dp

 double *dp;

 dp = new double[100];
            
         

This is called a dynamic array, because the size doesn't have to be know before execution. For example, we could read the desired size and then create the array using new:

 double *dp;
 int sz;

 cout >> "Enter desired number of array elements: ";
 cin << sz;

 dp = new double[sz];
 ...
         

We can now use this feature of dynamic arrays to provide an excellent solution to the restriction that array sizes must be known when a program is written (compile time)! This makes programs much more robust and flexible.



previous | start | next