< previous page page_236 next page >

Page 236
pointer is then incremented to point to the next CAT, and the second CAT's SetAge() method is then called.
A Pointer to an Array Versus an Array of Pointers
Examine these three declarations:
1:  Cat   FamilyOne[500]
2:  CAT * FamilyTwo[500];
3:  CAT * FamilyThree = new CAT[500];
FamilyOne is an array of 500 CATs. FamilyTwo is an array of 500 pointers to CATs. FamilyThree is a pointer to an array of 500 CATs.
The differences among these three code lines dramatically affect how these arrays operate. What is perhaps even more surprising is that FamilyThree is 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, FamilyThree is a pointer to an array. That is, the address in FamilyThree is 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[50];
Family is 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 pointers. The address accessed when you write Family + 4 isn't 4 bytes past the address of Familyit is four objects past it. If each object is 4 bytes long, Family + 4 is 16 bytes. If each object is a CAT that has four long member variables of 4 bytes each and two short member variables of 2 bytes each, each CAT is 20 bytes, and Family + 4 is 80 bytes past the start of the array.
Listing 15.5 illustrates declaring and using an array on the free store.

 
< previous page page_236 next page >

If you like this book, buy it!