C++ Primer For Java Programmers


Dynamic Arrays

<< | Table of Contents | >>
Arrays in C++ can also be created at runtime just as they are in Java. There are two approachs to creating dynamic arrays: C++ specific dynamic allocation or the original C allocation approach.

C++ Dynamic Arrays

To create a dynamic array using the C++ approach, the new operator is used as it is in Java. In the following example,

(:source lang=cpp:)
int *myGrades = new int[ NUM_GRADES ];
myGrades[ 0 ] = 85;
myGrades[ 1 ] = 90;
myGrades[ 2 ] = 87;
myGrades[ 3 ] = 65;
myGrades[ 4 ] = 91;

we create a five element int dynamic array as shown below

Note that the array itself is dynamic but it does not contain dynamic elements. You will also notice the use of the pointer notation to specify the array pointer variable.

Deleteing Dynamic Arrays. As with any dynamic variable, you are responsible for deallocation when the dynamic memory is no longer needed. The delete command is also used to delete a dynamic array.

(:source lang=cpp:)
delete myGrades;

You can only delete an array which was created using the new operator. Static arrays can not be delete since they are not dynamic and their pointer variables are constant.

C Dynamic Arrays

Dynamic Pointer Arrays


<< | Table of Contents | >>

Print - Changes - Search
Last modified: April 30, 2007, at 10:06 PM.