Writing Past the End of an Array ..................................................................
When you write a value to an element in an array, the compiler computes where to store
the value based on the size of each element and the subscript. Suppose that you ask to
write over the value at LongArray[5], which is the sixth element. The compiler multi-
plies the offset (5) by the size of each element—in this case, 4 bytes. It then moves that
many bytes (20) from the beginning of the array and writes the new value at that
location.
If you ask to write at LongArray[50], most compilers ignore the fact that no such ele-
ment exists. Rather, the compiler computes how far past the first element it should look
(200 bytes) and then writes over whatever is at that location. This can be virtually any
data, and writing your new value there might have unpredictable results. If you’re lucky,
your program will crash immediately. If you’re unlucky, you’ll get strange results much
later in your program, and you’ll have a difficult time figuring out what went wrong.
The compiler is like a blind man pacing off the distance from a house. He starts out at
the first house,MainStreet[0]. When you ask him to go to the sixth house on Main
Street, he says to himself, “I must go five more houses. Each house is four big paces. I
must go an additional 20 steps.” If you ask him to go to MainStreet[100]and Main
Street is only 25 houses long, he paces off 400 steps. Long before he gets there, he will,
no doubt, step in front of a truck. So be careful where you send him.
Listing 13.2 writes past the end of an array. You should compile this listing to see what
error and warning messages you get. If you don’t get any, you should be extra careful
when working with arrays!
410 Day 13
Arrays count from zero, not from one. This is the cause of many bugs in pro-
grams written by C++ novices. Think of the index as the offset. The first ele-
ment, such as ArrayName[0], is at the beginning of the array, so the offset is
zero. Thus, whenever you use an array, remember that an array with 10 ele-
ments counts from ArrayName[0]to ArrayName[9]. ArrayName[10]is an error.
NOTE
CAUTION Do not run this program; it might crash your system!