11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Storing Sequences in Arrays 99You may initialize all the elements in an array to a common value by listingonly that value. For example, the following initializes all 25 locations infloatArray to 1.0.float floatArray[25] = {1.0};Accessing too far into an arrayMathematicians start counting arrays with 1. Most program languages startwith an offset of 1 as well. C++ arrays begin counting at 0. The first member ofa C++ array is valueArray[0]. That makes the last element of a 128-integerarray integerArray[127] and not integerArray[128].Unfortunately for the programmer, C++ does not check to see whether theindex you are using is within the range of the array. C++ is perfectly happygiving you access to integerArray[200]. Our yard is only 128 integers long —that’s 72 integers into someone else’s yard. No telling who lives there andwhat he’s storing at that location. Reading from integerArray[200] willreturn some unknown and unpredictable value. Writing to that location generatesunpredictable results. It may do nothing — the house may be abandonedand the yard unused. On the other hand, it might overwrite some data,thereby confusing the neighbor and making the program act in a seeminglyrandom fashion. Or it might crash the program.The most common wrong way to access an array is to read or write locationintegerArray[128]. This is one integer beyond the end of the array.Although it’s only one element beyond the end of the array, reading or writingthis location is just as dangerous as using any other incorrect address.Using arraysOn the surface, the ArrayDemo program doesn’t do anything more than ourearlier, non-array-based programs did. True, this version can replay its inputby displaying the set of input numbers before calculating their sum, but thisfeature hardly seems earth shattering.Yet, the ability to redisplay the input values hints at a significant advantageto using arrays. Arrays allow the program to process a series of numbersmultiple times. The main program was able to pass the array of input valuesto displayArray() for display and then repass the same numbers tosumArray() for addition.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!