22A. Arrays


Review

A program needs to be able to use large chunks of memory, and arrays are a mechanism to support that.

We have seen the basics of arrays. An array is a numbered sequence of variables; variable numbers are called indices (singular: index). Expression A[i] indicates the variable in array A with index i.

Remember that the indices start at 0. If array A contains 4 variables, then they are A[0], A[1], A[2] and A[3]. The last index in an array of size n is n−1.


Arrays

Now we begin to look at arrays in more detail. C++ has an unusual way of treating arrays. It separates the issue of allocating an array from the issue of using an array.

Chunks

It is helpful to have a term for a piece of memory, possibly small or possibly quite large. Let's call it a chunk. A chunk has a starting address and a size. A chunk of integers might contain memory for 1 integer (4 bytes, for 32-bit integers) or for 1000 integers (4000 bytes).

An array is a pointer

In C++, an array is not a chunk. The definition of an array is:

An array is a pointer to the first item in a chunk of memory.

So, not only is an array not a chunk, it is not even a pointer to a chunk. It is a pointer to the first variable in a chunk. If A is an array, and you have allocated a chunk for it, then you get something like this:

For example, an array of integers is a pointer to the first integer variable in a chunk of some unspecified number of integers. Since a pointer to an integer has type int*, an array of integers must also have type int*. An array of real numbers has type double*, an array of characters has type char*, etc.

You can think of * as meaning array, as long as you remember that the "array" sometimes contains only one variable. There is no way for you to know just from type int* whether a pointer points to a single variable or to a large chunk. The presence or absence of other things after the first one in the memory is considered an allocation issue.

A pointer is an array

Since an array is a pointer, you can store that pointer into any pointer variable of the correct pointer type. An array of integers has type int*, so

  int  A[10];
  int* p = A;
  p[0] = 0;
makes variable p point to the first member of array A. Since an array is a pointer, a pointer is an array. Setting p[0] = 0 is equivalent to setting A[0] = 0, since pointers p and A are the same.


Exercises

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

  2. If array B is created by

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

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

  4. Is the following allowed?

      long  B[20];
      long* p = B;
    
    Answer

  5. Suppose that p has type int*. Is the following allowed?

      int k = p[4];
    
    Answer