< previous page page_227 next page >

Page 227
LISTING 15.1 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
14:          cout << i << :  << myArray[i] << \n;
15:       return 0;
16:    }

Output:
Value for myArray[0]:  3
Value for myArray[1]:  6
Value for myArray[2]:  9
Value for myArray[3]:  12
Value for myArray[4]:  15
0: 3
1: 6
2: 9
3: 12
4: 15
Analysis: Line 6 declares an array called myArray, which holds five integer variables. Line 7 establishes a loop that counts from 0 through 4, which is the proper set of offsets for a five-element array. The user is prompted for a value, and that value is saved at the correct offset into the array.
The first value is saved at myArray[0], the second at myArray[1], and so forth. The second for loop prints each value to the screen.
Arrays count from 0, not from 1. This is the cause of many bugs in programs written by C++ novices. Whenever you use an array, remember that an array with 10 elements counts from ArrayName[0] to ArrayName[9]. There is no ArrayName[10].

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 multiplies the offset5by the size of each elementin this case, 4. It then moves that many bytes20from the beginning of the array and writes the new value at that location.
If you ask to write at LongArray[50], the compiler ignores the fact that there is no such element. It computes how far past the first element it should be200 bytesand 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

 
< previous page page_227 next page >

If you like this book, buy it!