Sams Teach Yourself C++ in 21 Days

(singke) #1
This is a classic example of code that is best understood by putting it into a debugger and
stepping through its execution.
Pointer arithmetic is used in a number of places in this listing. In this listing, you can see
that by subtracting one pointer from another (as on line 53), you determine the number
of elements between the two pointers. In addition, you saw on line 55 that incrementing
a pointer shifts it to the next element within an array rather than just adding one. Using
pointer arithmetic is very common when working with pointers and arrays, but it is also a
dangerous activity and needs to be approached with respect.

Declaring Arrays on the Free Store ....................................................................


It is possible to put the entire array on the free store, also known as the heap. You do this
by creating a pointer to the array. Create the pointer by calling newand using the sub-
script operator. The result is a pointer to an area on the free store that holds the array. For
example,
Cat *Family = new Cat[500];
declares Familyto be a pointer to the first element in an array of 500 Cats. In other
words,Familypoints to—or has the address of—Family[0].
The advantage of using Familyin this way is that you can use pointer arithmetic to
access each member of Family. For example, you can write
Cat *Family = new Cat[500];
Cat *pCat = Family; //pCat points to Family[0]
pCat->SetAge(10); // set Family[0] to 10
pCat++; // advance to Family[1]
pCat->SetAge(20); // set Family[1] to 20
This declares a new array of 500 Cats and a pointer to point to the start of the array.
Using that pointer, the first Cat’s SetAge()function is called with a value of 10. The
pointer is then incremented. This causes the pointer to be incremented to point to the
next Catobject in the array. The second Cat’s SetAge()method is then called with a
value of 20.

A Pointer to an Array Versus an Array of Pointers ........................................


Examine the following three declarations:
1: Cat FamilyOne[500];
2: Cat * FamilyTwo[500];
3: Cat * FamilyThree = new Cat[500];

426 Day 13

Free download pdf