5.11.1 Arrays


Arrays

An array is a collection of consecutive items in memory. Each item is referred to by its index. The indices always start at 0. For example, an array of 5 items has indices 0, 1, 2, 3 and 4.

All of the items in an array must have the same type. For example, you can have an array of ints, an array of doubles, etc.

Creating an array in the run-time stack

Statement
  int A[10];
creates an array of ints within the current function's run-time stack frame and names it A. In general, the form is
  T name[size];
where T is the type of each variable in the array, name is the array's name and size is the number of items. For example,
  double stuff[100];
creates an array called stuff of size 100, where each variable in the array has type double.

A[i]

Expression A[i] refers to the variable at index i in array A. Be sure to remember that the indices start at 0. So if an array has size n then the last index is n−1. For example,
  char str[10];
  str[0] = 'a';
  str[1] = 'b';
creates an array of characters called str and stores 'a' into str[0] and 'b' into str[1].

The index can be given by any expression that yields an integer. For example, str[2*k + 1] is allowed, as long as k is an integer.


Watch out: array bounds errors

If your program uses a nonexistent index in an array, the error will not automatically be detected. The program just uses the memory that would have been the correct memory to use if the array did have that index. But that means you are using a dangling pointer, and its effects are unpredictable.

Be careful with arrays. Ensure that you do not use a nonexistent index.



Example

The following main function reads a list of integers from the standard input until it sees integer 0. Then it writes them to the standard output backwards. It is a silly function, but it illustrates use of arrays.

  #include <cstdio>
  using namespace std;

  const int maxNums = 100;

  int main(int argc, char** argv)
  {
    int A[maxNums];
    int i, howmany;

    //----------------------------------------------
    // Read the numbers into array A, stopping at 0.
    // Refuse to put too many values into the array.
    //----------------------------------------------

    for(i = 0; i < maxNums; i++)
    {
      scanf("%i", &(A[i]));
      if(A[i] == 0) 
      {
        break;
      }
    }
    howmany = i;

    //----------------------------------------------
    // Write the numbers out backwards.
    //----------------------------------------------
    
    for(i = howmany - 1; i >= 0; i--)
    {
      printf("%i\n", A[i]);
    }

    return 0;
  }  


Exercises

  1. How do you refer to the variable at index k in array W? Answer

  2. What happens if you use an index that is not an allowed index for an array? Answer

  3. If array B is created by

      double B[4];
    
    what are the allowed indices for B? Answer

  4. Write statements that create an array of 100 ints and store 0 into each variable in the array. Answer