Managing Arrays and Strings 423
13
to display a count starting at 1 instead. On line 34, the pointer is accessed by using the
index,Family[i]. That address is then used to access the GetAge()method.
In this example, the array Familyand all its pointers are stored on the stack, but the 500
Catobjects that are created are stored on the free store.
A Look at Pointer Arithmetic—An Advanced Topic ..........................................
On Day 8, “Understanding Pointers,” you initially learned about pointers. Before contin-
uing with arrays, it is worth coming back to pointers to cover an advanced topic—pointer
arithmetic.
There are a few things that can be done mathematically with pointers. Pointers can be
subtracted, one from another. One powerful technique is to point two pointers at different
elements in an array and to take their difference to see how many elements separate the
two members. This can be very useful when parsing arrays of characters, as illustrated in
Listing 13.7.
LISTING13.7 Illustrates How to Parse Out Words from a Character String
0: #include <iostream>
1: #include <ctype.h>
2: #include <string.h>
3:
4: bool GetWord(char* theString,
5: char* word, int& wordOffset);
6:
7: // driver program
8: int main()
9: {
10: const int bufferSize = 255;
11: char buffer[bufferSize+1]; // hold the entire string
12: char word[bufferSize+1]; // hold the word
13: int wordOffset = 0; // start at the beginning
14:
15: std::cout << “Enter a string: “;
16: std::cin.getline(buffer,bufferSize);
17:
18: while (GetWord(buffer, word, wordOffset))
19: {
20: std::cout << “Got this word: “ << word << std::endl;
21: }
22: return 0;
23: }
24: