Pointers/Memory Allocation   «Prev  Next»
Lesson 11 A dynamic array
Objective Write a function that reverses a string using storage allocated with new.

C++ Dynamic Array

The following example uses the operators new and delete to dynamically allocate an array.

Program dissection

Move your mouse cursor over the highlighted lines of code below to receive more information with respect to the role of each function.
C++ dynamic Array
  1. The pointer variable "data" is used as the base address of a dynamically allocated array whose number of elements is the value of "size."
  2. The user is prompted for the integer value "size."
  3. The "new" operator is used to allocate storage from free store capable of storing a variable of type int[size]. On a system where integers take 2 bytes, this would allocate 2 x size, bytes.|At this point, ,data, is assigned the base|address of this store
  4. The second ,assert, guarantees that allocation succeeded. In newer C++ systems, when the ,new, operator fails, an exception is thrown and the program is|automatically aborted.
  5. This statement initializes the values of the, data, array and prints them.
  6. The operator ,delete, returns the storage associated with the pointer variable data, to free store. This can be done only with variables allocated by new. The brackets form is used because the corresponding allocation was of an array.

Dynamic Array Dissection

New Storage Allocation - Exercise

Click the Exercise link below to write a function that reverses a string using storage allocated with the operator new.
New Storage Allocation - Exercise