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 Family—it 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 heap.
Cat #1: 1 Cat #2: 3 Cat #3: 5 ... Cat #499: 997 Cat #500: 999
Line 24 declares the array Family, which holds 500 CAT objects. The entire array is created on the heap with the call to new CAT[500]. |
Technically, line 24 declares an unnamed array on the heap and returns the address of its first element to the pointer Family. It is customary to refer to that pointer as the array itself. In fact, whenever you declare an array (even on the stack) the array name is really just a pointer to the first element. |
Each CAT object added to the array also is created on the heap (line 29). Note, however, that the pointer isn't added to the array this time; the object itself is. This array isn't an array of pointers to CATs—it is an array of CATs.
18.117.138.178