Pointers/Memory Allocation   «Prev 

C++ Dynamic Array

The C array model is pointer-based and one-dimensional without bounds checking.\This lack of dynamic multidimensional arrays means the programmer must spend more time and effort implementing them using the one-dimensional storage mapping function that is C's paradigm.
Development and use of dynamic arrays also require significant work and are not supported in C. C++ retains the array handling of C; however, abstract data types provide a satisfactory means of transparently implementing general arrays. Multidimensional, dynamic, and bounds-checked arrays can be implemented in libraries. In order to request dynamic memory the new operator is used.
new is followed by a data type specifier and if a sequence of more than one element is required, then the number of these is placed within brackets [].
It returns a pointer to the beginning of the new block of memory allocated. Its form is:

pointer = new type
pointer = new type [numElements]

The first expression is used to allocate memory to contain one single element of type type.
The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:

1 int * panda;
2 panda = new int [5];

Dynamically assigns Space

In this case, the system dynamically assigns space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to panda. Therefore, panda points to a valid block of memory with space for five elements of type int.

C++ How to Program