Arrays

Array Definition

An array is a data form that can hold several values all of one type.

Array Declaration

The general form for declaring an array in C++ is this:

typeName arrayName[arraySize];

For example,
short months[12];

An array is a derived type because it is based on some other type.

One can access the array elements individually. The way to do this is to use a subscript, or index, to number the elements. C++ array numbering starts with 0, using a barcket notation with the index to specify an array element.
For example, months[0] is the first element of the months array, and months[11] is the last element.
Note that the index of the last element is one less than the size of the array.

Array Initialization

C++ lets you initialize array elements within the declaration statement.
int eggCosts[3] = { 4, 5, 3 };
Simply provide a comma-seperated list of values ( the initialization list) enclosed in braces. The spaces in the list are optional. If you don't initialize an array that's defined inside a function, the element values remain undefined. The element takes on whatever value previously resided at that location in memory.

The sizeof operator when used with an array name, will return the number of bytes in the whole array. But if you use the sizeof with an array element, you get the size, in bytes, of the element.

Initialization Rules
  1. You can use the initialization form only when defining the array. You cannot use it later.
    int cards[4] = {3, 6, 8, 10}; // okay =)
    int hand[4]; // okay =)
    hand[4] = {5, 6, 7, 9}; // not allowed =(
  2. You cannot assign one array wholesale to another.
    hand = cards; // not allowed =(
  3. However, you always can use subscripts and assign values to the elements of an array individually.
    int yams[3]
    yams[0] = 7;
    yams[1] = 7;
    yams[2] = 7;
  4. When initializing an array, you can provide fewer values than array elements.
    E.g. float hotelTips[5] = {5.0, 2.5};
    If you partially initialize an array, the compiler sets the remaining elements to zero. Thus its easy to initialize all the elements of an array to zero, just initialize the first element explicitly to zero and then let the compiler initialize the remaining elements to zero:
    E.g. float totals[500] = {0};
  5. If you leave the square brackets empty ([]) when you initialize an array, the C++ compiler counts the elements for you.