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 9: Taking a Second Look at C++ Pointers 129int main(int nNumberofArgs, char* pszArgs[]){int array[] = {4, 3, 2, 1};displayArray(array, 4);}// wait until user is ready before terminating program// to allow the user to see the program resultssystem(“PAUSE”);return 0;The output from this program isThe value of the array is:0: 41: 32: 23: 1Press any key to continue . . .You may think this pointer conversion is silly; however, the pointer version ofdisplayArray() is actually more common among C++ programmers in theknow than the array version. For some reason, C++ programmers don’t seemto like arrays.The use of pointers to access arrays is nowhere more common than in theaccessing of character arrays.Expanding pointer operations to a stringA null terminated string is simply a character array whose last character is anull. C++ uses the null character at the end to serve as a terminator. This nullterminated array serves as a quasi-variable type of its own. (See Chapter 7 foran explanation of string arrays.) Often C++ programmers use character pointersto manipulate such strings. The following code examples compare thistechnique to the earlier technique of indexing in the array.Character pointers enjoy the same relationship with a character array that anyother pointer and array share. However, the fact that strings end in a terminatingnull makes them especially amenable to pointer-based manipulation, asshown in the following DisplayString() program:// DisplayString - display an array of characters both// using a pointer and an array index#include #include #include

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

Saved successfully!

Ooh no, something went wrong!