Dynamic Array

Prev: Introduction

The new[] Operator

The new[] operator creates or modifies the depth of an array. Consider the following example:

 
int int_array[]; // declare an integer array
...
int_array = new[25]; // creates 25-deep array 
In the above example, after the declaration of int_array no space has been allocated for it and hence using any array element is illegal. The memory allocation for the elements are not done until the new operator is encountered. At this point, it is legal to use the array indexes 0 through 24.

Another use of the new[] operator is to modify an existing dynamic array. In the following example, int_array2 is a second dynamic array.

 
// Declare an integer array
int int_array[];
// Declare another integer array
int int_array2[]; 
...
// Creates 25-deep array for int_array
int_array = new[25];
...
// Creates 50-deep array for int_array2
// and then copies first 25 elements from int_array
int_array2 = new[50](int_array);
In the above example, the last line indicates how new[50] creates an array of 50 elements for int_array2. Then the (int_array) part copies the existing int_array into first 25 locations of int_array2. Rest 25 locations of int_array will remain empty.

What will happen if int_array2 has less number of elements, say 15, than int_array? In that case, only the first 15 elements of int_array will be copied to int_array2.

A clever use of the new[] operator in the above manner lets you modify the size of an existing dynamic array.

 
// declare an integer array
int int_array[];
...
// creates a 25-deep array
int_array = new[25]; 
...
// deletes the last 10 elements 
int_array = new[15](int_array); 
...
// increases the size of int_array to 30
// preservng the old values
int_array = new[30](int_array); 

The method size()

The method size() returns the current size of a dynamic array as an integer.

int current_size;
...
current_size = int_array.size();
If a dynamic array is not created yet, then the returned size will be zero.

The method delete()

The method delete() simply deletes all the elements of a synamic array and leaves it at the state of declaration when the array was not created.

int_array.delete();
The size of a deleted dynamic array, as can be expected, is zero.

Prev: Introduction

Share/Save/Bookmark



Verification Management
Join Verification Management Group


Book of the Month


From Our Press