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.

126Part II: Becoming a Functional C++ ProgrammerIn this case, offset is of type long. (Although not listed in Table 9-1, C++ alsosupports operators related to addition and subtraction, such as ++ and +=.)The real estate memory model (which I use so effectively in Chapter 8, if I dosay so myself) is useful to explain how pointer arithmetic works. Consider acity block in which all houses are numbered sequentially. The house next to123 Main Street has the address 124 Main Street (or 122 if you go backward,like Hebrew and Arabic).Now it’s pretty clear that the house four houses down from 123 Main Streetmust be 127 Main Street; thus, you can say 123 Main + 4 = 127 Main.Similarly, if I were to ask how many houses are there from 123 Main to 127Main, the answer would be four — 127 Main - 123 Main = 4. (Just asan aside, a house is zero houses from itself: 123 Main - 123 Main = 0.)Extending this concept one step further, it makes no sense to add 123 MainStreet to 127 Main Street. In similar fashion, you can’t add two addresses, norcan you multiply an address, divide an address, square an address, or takethe square root — you get the idea.Re-examining arrays in lightof pointer variablesNow return to the wonderful array for just a moment. Once again, my neighborhoodcomes to mind. An array is just like my city block. Each element ofthe array corresponds to a house on that block. Here, however, the array elementsare measured by the number of houses from the beginning of the block(the street corner). Say that the house right on the corner is 123 Main Street,which means that the house one house from the corner is 124 Main Street,and so on. Using array terminology, you would say cityBlock[0] is 123 MainStreet, cityBlock[1] is 124 Main Street, and so on.Take that same model back to the world of computer memory. Consider thecase of an array of 32 1-byte characters called charArray. If the first byte ofthis array is stored at address 0x110, the array will extend over the range0x110 through 0x12f. charArray[0] is located at address 0x110,charArray[1] is at 0x111, charArray[2] at 0x112, and so on.Take this model one step further to the world of pointer variables. After executingthe expressionptr = &charArray[0];the pointer ptr contains the address 0x110. The addition of an integer offsetto a pointer is defined such that the relationships shown in Table 9-2 are true.Table 9-2 also demonstrates why adding an offset n to ptr calculates theaddress of the nth element in charArray.

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

Saved successfully!

Ooh no, something went wrong!