21.4.  Introduction to Arrays

[ fromfile: memoryaccess.xml id: arrays ]

An array is a sequence of contiguous memory cells, all of the same size. Each cell is called an array element or entry.

When an array is declared, the size of the array must be made known. This can be done explicitly or by initialization:

int a[10]; // explicitly creates uninitialized cells a[0], a[1],..., a[9]
int b[] = {1,3,5,7}; // implicitly creates and initializes b[0],..., b[3]

The array name is an alias for a const typed pointer to the first cell of the array. A pointer declaration such as

 int* ptr; 

only creates the pointer variable. There is no automatic default initialization of pointer variables. It is an error to attempt to dereference an uninitialized pointer.

Array indices are relative offsets from the base address:

 a[k] is equivalent to *(a + k) 

The following bit of code demonstrates an interesting aspect of array indices.

Example 21.4. src/pointers/pathology/pathologydemo2.cpp

#include <iostream>
using namespace std;
int main(){
  int a[] = {10, 11, 12, 13, 14, 15};

  int* b = a + 1;
  cout << "a[3] = " << a[3] << '\n'
       << "b[3] = " << b[3] << endl;

  //It gets even worse.
  int c = 123;
  int* d = &c;
  cout << "d[0] = " << d[0] << '\n'
       << "d[1] = " << d[1] << '\n'
       << "d[2] = " << d[2] << endl;

}

Compiling and running produces the following output.

pointers/pathology> g++ -ansi -pedantic -Wall pathologydemo2.cpp 
pointers/pathology> 
a[3] = 13
b[3] = 14
d[0] = 123
d[1] = -1075775392
d[2] = -1219610235

Notice that neither b nor d was declared as an array, but the compiler allows us to use the subscript [] operator anyway. c is an ordinary int variable and d is an ordinary int pointer. d[0], d[1], and d[2] are all undefined but the compiler did not even give any warnings about their presence in the program – even with the three commandline switches that we used.

There is a special syntax for defining a dynamic array consisting of a given number of elements of some type.

   uint n;
   ArrayType* pt;
   pt = new ArrayType[n];

This version of new allocates n contiguous blocks of memory, each of size sizeof(ArrayType) and returns a pointer to the first block. Each element of the newly allocated array is given default initialization. To properly deallocate this array, it is necessary to use the syntax:

delete[] pt;

Using delete without the empty brackets to delete a dynamic array produces undefined results.

We discuss exceptions and what happens when a request for dynamic memory cannot be fulfilled by the system in a separate article[118] in our dist directory.



[118] articles/exceptions.html