Indexing into an Array in C++ - dummies

By Stephen R. Davis

In C++, you must provide an index to access a specific element within the array. An index must be a counting type (such as int), as demonstrated here:

nScores[11] = 10;

This is akin to the way that rental cars are numbered. However, unlike humans, C++ starts with 0 when numbering its arrays. Thus the first score in the array nScores is nScores[0].

So how does this work exactly? Well, think of a rental car parking lot. The figure shows how rental cars are typically numbered in their parking lots. The first car in row B carries the designation B1. To find B11, simply move your gaze ten cars to the right.


C++ does a similar thing. To execute the statement nScores[11] = 10, C++ starts with the address of the first element in nScores. It then moves to the right 11 spaces and stores a 10 at that location. This is shown graphically in the following figure.


The fact that C++ starts counting at zero leads to a point that always confuses beginners. The statement

int nScores[100];

declares 100 scores, which are numbered from 0 to 99. The expression

nScores[100] = 0;  // this is an error

zeroes out the first element beyond the end of the array. The last element in the array is nScores[99]. The C++ compiler will not catch this error and will happily access this non-element, which very often leads to the program accessing some other variable by mistake. This type of error is very hard to find because the results are so unpredictable.