Managing Arrays and Strings 421
13
dimension is incremented only after the second dimension has gone through all of its
increments. Then counting for the second dimension starts over.
A Word About Memory
When you declare an array, you tell the compiler exactly how many objects you expect to
store in it. The compiler sets aside memory for all the objects, even if you never use it.
This isn’t a problem with arrays for which you have a good idea of how many objects
you’ll need. For example, a chessboard has 64 squares, and cats have between 1 and 10
kittens. When you have no idea of how many objects you’ll need, however, you must use
more advanced data structures.
This book looks at arrays of pointers, arrays built on the free store, and various other col-
lections. You’ll see a few advanced data structures, but you can learn more in the book
C++ Unleashed from Sams Publishing. You can also check out Appendix E, “A Look at
Linked Lists.”
Two of the great things about programming are that there are always more things to
learn and that there are always more books from which to learn them.
Building Arrays of Pointers ................................................................................
The arrays discussed so far store all their members on the stack. Usually, stack memory
is more limited, whereas free store memory is much larger. It is possible to declare each
object on the free store and then to store only a pointer to the object in the array. This
dramatically reduces the amount of stack memory used. Listing 13.6 rewrites the array
from Listing 13.4, but it stores all the objects on the free store. As an indication of the
greater memory that this enables, the array is expanded from 5 to 500, and the name is
changed from Litterto Family.
LISTING13.6 Storing an Array on the Free Store
0: // Listing 13.6 - An array of pointers to objects
1:
2: #include <iostream>
3: using namespace std;
4:
5: class Cat
6: {
7: public:
8: Cat() { itsAge = 1; itsWeight=5; }
9: ~Cat() {} // destructor
10: int GetAge() const { return itsAge; }
11: int GetWeight() const { return itsWeight; }
12: void SetAge(int age) { itsAge = age; }