22G. Summary

An array is a pointer to the first item in a chunk of memory that might contain any number of items. An array of integers has type int*. An array of doubles has type double*. You can perform arithmetic with pointers. A + i is the same as &(A[i]), the address where A[i] is stored.

It is important to keep the pointer nature of arrays in mind. Copying an array in an assignment statement such as B = A only copies the pointer, not the chunk of memory that the pointer points to. That is in the spirit of Java, where all objects are pointers to chunks of memory, and objects are not implicitly copied.

C++ has a major difference from Java when it comes to array indices that are out of bounds. In Java, such indices are automatically caught. In C++, they are not. It is up to you to ensure that your arrays are large enough and that your array indices are sensible.

In C++, you can create an array either in the frame of the current function or in the heap. Use expression new int[n] to allocate an array of n integers in the heap. Its value is the address of the first of those integers, so new int[n] has type int*. If you do not know how large an array needs to be, make its size a named constant so that the size is easy to change by changing the value of that constant.

To delete the chunk of an array A that was allocated in the heap, say

  delete [] A;