C++

Arrays Of Pointers

The arrays discussed so far store all their members on the stack. Usually stack memory is severely limited, whereas free store memory is far 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 11.6 rewrites the array from Listing 11.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 Litter to Family.

Listing 11.6. Storing an array on the free store.

1: // Listing 11.6 - An array of pointers to objects

2:

3: #include <iostream.h>

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; }

13:

14: private:

15: int itsAge;

16: int itsWeight;

17: };

18:

19: int main()

20: {

21: CAT * Family[500];

22: int i;

23: CAT * pCat;

24: for (i = 0; i < 500; i++)

25: {

26: pCat = new CAT;

27: pCat->SetAge(2*i +1);

28: Family[i] = pCat;

29: }

30:

31: for (i = 0; i < 500; i++)

32: {

33: cout << "Cat #" << i+1 << ": ";

34: cout << Family[i]->GetAge() << endl;

35: }

36: return 0;

37: }

OUTPUT:

Cat #1: 1

Cat #2: 3

Cat #3: 5

...

Cat #499: 997

Cat #500: 999

ANALYSIS: The CAT object declared in lines 5-17 is identical with the CAT object declared in Listing 11.4. This time, however, the array declared in line 21 is named Family, and it is declared to hold 500 pointers to CAT objects.

In the initial loop (lines 24-29), 500 new CAT objects are created on the free store, and each one has its age set to twice the index plus one. Therefore, the first CAT is set to 1, the second CAT to 3, the third CAT to 5, and so on. Finally, the pointer is added to the array.

Because the array has been declared to hold pointers, the pointer—rather than the dereferenced value in the pointer—is added to the array.

The second loop (lines 31 and 32) prints each of the values. 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 Family and all its pointers are stored on the stack, but the 500 CATs that are created are stored on the free store.

Back to Index