Sams Teach Yourself C++ in 21 Days

(singke) #1
You declare an array by writing the type, followed by the array name and the subscript.
The subscript is the number of elements in the array, surrounded by square brackets. For
example,
long LongArray[25];
declares an array of 25 longintegers, named LongArray. When the compiler sees this
declaration, it sets aside enough memory to hold all 25 elements. If each longinteger
requires four bytes, this declaration sets aside 100 contiguous bytes of memory, as illus-
trated in Figure 13.1.

408 Day 13


FIGURE13.1
Declaring an array.

4 bytes

100 bytes

Accessing Array Elements..............................................................................


You access an array element by referring to its offset from the beginning of the array.
Array element offsets are counted from zero. Therefore, the first array element is referred
to as arrayName[0]. In the LongArrayexample,LongArray[0]is the first array element,
LongArray[1]the second, and so forth.
This can be somewhat confusing. The array SomeArray[3]has three elements. They are
SomeArray[0],SomeArray[1], and SomeArray[2]. More generally,SomeArray[n]has n
elements that are numbered SomeArray[0]through SomeArray[n-1]. Again, remember
that this is because the index is an offset, so the first array element is 0 storage locations
from the beginning of the array, the second is 1 storage location, and so on.
Therefore,LongArray[25]is numbered from LongArray[0]through LongArray[24].
Listing 13.1 shows how to declare an array of five integers and fill each with a value.

Starting with today’s listings, the line numbers will start with zero. This is to
help you remember that arrays in C++ start from zero!

NOTE
Free download pdf