"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." | ||
--Stan Kelly-Bootle |
An array is an indexed collection of objects. Each object in an array has the same type.
ElementType theArray[numberofElements]; Account allTheAccounts[2000];
Each element is initialised by calling the default constructor. If there is no default constructor, we could use (provided we use the correct number of elements):
int main() { Account someAccounts[3] = { Account("Tom", 20.00, 123456), Account("Richard", 55.00, 123457), Account("Harry", 99.00, 123458) };Account *p = &someAccounts[0];
someAccounts[2].display(); //displays Harry
p->display(); //displays Tom
(++p)->display(); //displays Richard
(p+1)->display(); //displays Harry
//Warning! The pointer p now points at Richard, not Tom!
}
The full source code for this example is listed in
AccountArrayExample.cpp
.
Pointers can be used to allocate arrays of objects using the new
keyword.
Account *ptr; ptr = new Account[10];
A pointer to an array of objects has the exact same form as a pointer to
an object. There is no way to distinguish between a pointer to a type and a pointer to an
array of that type, except by careful coding. To destroy the array use delete[] ptr;
If ptr
points to an array then delete ptr;
is undefined. Here is an
example of using delete[]
on an array of your own objects:
using_delete.cpp
© 2006
Dr. Derek Molloy
(DCU).