Managing Arrays and Strings 427
13
FamilyOneis an array of 500 Catobjects. FamilyTwois an array of 500 pointers to Cat
objects. FamilyThreeis a pointer to an array of 500 Catobjects.
The differences among these three code lines dramatically affect how these arrays oper-
ate. What is perhaps even more surprising is that FamilyThreeis a variant of FamilyOne,
but it is very different from FamilyTwo.
This raises the thorny issue of how pointers relate to arrays. In the third case,
FamilyThreeis a pointer to an array. That is, the address in FamilyThreeis the address
of the first item in that array. This is exactly the case for FamilyOne.
Pointers and Array Names..............................................................................
In C++, an array name is a constant pointer to the first element of the array. Therefore, in
the declaration
Cat Family[500];
Familyis a pointer to &Family[0], which is the address of the first element of the array
Family.
It is legal to use array names as constant pointers, and vice versa. Therefore,Family + 4
is a legitimate way of accessing the data at Family[4].
The compiler does all the arithmetic when you add to, increment, and decrement point-
ers. The address accessed when you write Family + 4isn’t four bytes past the address
of Family—it is four objects. If each object is four bytes long,Family + 4is 16 bytes
past the start of the array. If each object is a Catthat has four longmember variables of
four bytes each and two shortmember variables of two bytes each, each Catis 20 bytes,
and Family + 4is 80 bytes past the start of the array.
Listing 13.8 illustrates declaring and using an array on the free store.
LISTING13.8 Creating an Array by Using new
0: // Listing 13.8 - An array on the free store
1:
2: #include <iostream>
3:
4: class Cat
5: {
6: public:
7: Cat() { itsAge = 1; itsWeight=5; }
8: ~Cat();
9: int GetAge() const { return itsAge; }
10: int GetWeight() const { return itsWeight; }