5.11.1 Arrays


Arrays

An array is a collection of consecutive items in memory. Each item is referred to by its index in the array. 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.

Fixed array sizes should be named constants

The preceding example creates arrays of size 10 and 100. But if you need to create an array of a fixed size, always make the size a named constant. For example, write
  const int nameMax = 100;
and, to create an array, write
  char name[nameMax];
You want to have a single point of modification. Wherever you need to refer to nameMax, write nameMax, not 100. If you decide to change nameMax to 200, you should only need to change the line that defines constant nameMax.

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.

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


Passing an array to a function

In the heading of a function definition, write [] after the name of a parameter to indicated that the parameter is an array. See the example below.

An array is never copied automatically. When an array is passed as a parameter, the function uses the callers array.



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;

  // ReadNumbers(A) reads numbers up to a 0.  It stores
  // the first value read into A[0], the second value
  // into A[1], etc.
  //
  // ReadNumbers returns the number of values that it read,
  // excluding the 0 at the end.

  void readNumbers(int A[])
  {
    int i;

    //----------------------------------------------
    // 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;
      }
    }
    return i;
  }

  // WriteNumbers(A, howmany) writes A[0], ...,
  // A[howmany-1], each on a separate line.

  void writeNumbers(int A[], int howmany)
  {
    for(i = howmany - 1; i >= 0; i--)
    {
      printf("%i\n", A[i]);
    }

  }

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

    howmany = readNumbers(A);
    writeNumbers(A, howmany);
    
    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