Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 411

13


LISTING13.2 Writing Past the End of an Array


0: //Listing 13.2 - Demonstrates what happens when you write
1: // past the end of an array
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: // sentinels
8: long sentinelOne[3];
9: long TargetArray[25]; // array to fill
10: long sentinelTwo[3];
11: int i;
12: for (i=0; i<3; i++)
13: {
14: sentinelOne[i] = 0;
15: sentinelTwo[i] = 0;
16: }
17: for (i=0; i<25; i++)
18: TargetArray[i] = 10;
19:
20: cout << “Test 1: \n”; // test current values (should be 0)
21: cout << “TargetArray[0]: “ << TargetArray[0] << endl;
22: cout << “TargetArray[24]: “ << TargetArray[24] << endl << endl;
23:
24: for (i = 0; i<3; i++)
25: {
26: cout << “sentinelOne[“ << i << “]: “;
27: cout << sentinelOne[i] << endl;
28: cout << “sentinelTwo[“ << i << “]: “;
29: cout << sentinelTwo[i]<< endl;
30: }
31:
32: cout << “\nAssigning...”;
33: for (i = 0; i<=25; i++) // Going a little too far!
34: TargetArray[i] = 20;
35:
36: cout << “\nTest 2: \n”;
37: cout << “TargetArray[0]: “ << TargetArray[0] << endl;
38: cout << “TargetArray[24]: “ << TargetArray[24] << endl;
39: cout << “TargetArray[25]: “ << TargetArray[25] << endl << endl;
40: for (i = 0; i<3; i++)
41: {
42: cout << “sentinelOne[“ << i << “]: “;
43: cout << sentinelOne[i]<< endl;
44: cout << “sentinelTwo[“ << i << “]: “;
45: cout << sentinelTwo[i]<< endl;
46: }
47:
48: return 0;
49: }
Free download pdf