Declaring Arrays

Arrays occupy space in memory. The programmer specifies the type of the elements and the number of elements required by an array as follows:

type arrayName [ arraySize ];


and the compiler reserves the appropriate amount of memory. The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 12 elements for integer array c, use the declaration

int c[ 12 ]; // c is an array of 12 integers

Memory can be reserved for several arrays with a single declaration. The following declaration reserves 100 elements for the integer array b and 27 elements for the integer array x.

int b[ 100 ], // b is an array of 100 integers
 x[ 27 ]; // x is an array of 27 integers

Good Programming Practice 7.1

We prefer to declare one array per declaration for readability, modifiability and ease of commenting.

Arrays can be declared to contain values of any non-reference data type. For example, an array of type char can be used to store a character string. Until now, we have used string objects to store character strings. Section 7.4 introduces using character arrays to store strings. Character strings and their similarity to arrays (a relationship C++ inherited from C), and the relationship between pointers and arrays, are discussed in Chapter 8.





C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net