Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 17,InputNumberis put into the array. This is safe the first time in because you
know you have room at this point. On line 19, a check is done to see if this is the last
element that the array has room for. If there is room, control passes to line 35; otherwise,
the body of the ifstatement is processed in order to increase the size of the array (lines
20–34).
A new array is created on line 21. This array is created to hold five more elements
(AllocationSize) than the current array. Lines 24–29 then copy the old array to the new
array using array notation (you could also use pointer arithmetic).
Line 31 deletes the old array and line 32 then replaces the old pointer with the pointer to
the larger array. Line 33 increases the MaximumElementsAllowedto match the new larger
size.
Lines 39–42 display the resulting array.

432 Day 13


DOremember that an array of nitems is
numbered from zero through n–1.
DOuse array indexing with pointers that
point to arrays.
DO use delete[]to remove an entire
array created on the free store. Using
just deletewithout the []only deletes
the first element.

DON’Twrite or read past the end of an
array.
DON’Tconfuse an array of pointers with
a pointer to an array.
DON’T forget to delete any memory you
allocate using new.

DO DON’T


charArrays and Strings ......................................................................................


There is a type of array that gets special attention. This is an array of characters that is
terminated by a null. This array is considered a “C-style string.” The only C-style strings
you’ve seen until now have been unnamed C-style string constants used in coutstate-
ments, such as
cout << “hello world”;
You can declare and initialize a C-style string the same as you would any other array. For
example:
char Greeting[] =
{ ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’,’o’,’r’,’l’,’d’,’\0’ };
In this case,Greetingis declared as an array of characters and it is initialized with a
number of characters. The last character,‘\0’, is the null character, which many C++
Free download pdf