O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Declaring Arrays on the Heap

It is possible to put the entire array on the heap, also known as the heap. You do this by calling new and using the subscript operator. The result is a pointer to an area on the heap that holds the array. For example:

CAT *Family = new CAT[500];

declares Family to be a pointer to the first in an array of 500 CATs. In other words, Family points to—or has the address of—Family[0].

The advantage of using Family in this way is that you can use pointer arithmetic to access each member of Family. For example, you can write

CAT *Family = new CAT[500];
CAT *pCat = Family;              // pCat points to Family[0]
pCat->SetAge(10);                // set Family[0] to 10
pCat++;                          // advance to Family[1]
pCat->SetAge(20);                // set Family[1] to 20

This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required