CPlusOOP
SiteMap
Building C++ Classes
Programming C++
Pointers/Memory Allocation
«Prev
Next»
Function Prototypes
C++ Core
Convert C program--> C++
Using IO Stream - Exercise
Similarities in C/C++
Program Structure Differences
C++ Boolean Expressions
C++ String Functions
C++ improves casts
Declarations enumerated Types
Initializing enumerated lists
Declaration Scope
Preferred Comment Style
Differences Similarities C/C++
Basic C++ Quiz
Scope of Function
Functions Variables - Conclusion
Functions Scope - Quiz
Anonymous Namespaces
Pointers Memory Allocation
C++ const keyword
const pointer argument
reference Declarations
Call by Reference
C++ Generic Pointer
void formal Parameter
Free Store Operators
C++ new Operator
C++ delete Operator
Dynamic Array
Dynamic multi-dimensional
array allocation Function
array deallocate Function
findmax Function
C++ main function
memory Allocation Conclusion
Pointers Memory Allocation - Quiz
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.
The pointer variable "data" is used as the base address of a dynamically allocated array whose number of elements is the value of "size."
The user is prompted for the integer value "size."
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
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.
This statement initializes the values of the, data, array and prints them.
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