13.3.1. Output of char * Variables

C++ determines data types automatically—an improvement over C, but this feature sometimes “gets in the way.” For example, suppose we want to print the address stored in a char * pointer. The << operator has been overloaded to output a char * as a null-terminated C-style string. To output the address, you can cast the char * to a void * (this can be done to any pointer variable). Figure 13.3 demonstrates printing a char * variable in both string and address formats. The address prints here as a hexadecimal (base-16) number—in general, the way addresses print is implementation dependent. To learn more about hexadecimal numbers, see Appendix D. We say more about controlling the bases of numbers in Section 13.6.1 and Section 13.7.4.


 1   // Fig. 13.3: fig13_03.cpp
 2   // Printing the address stored in a char * variable.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      const char *const word = "again";
 9
10      // display value of char *, then display value of char *
11      // after a static_cast to void *
12      cout << "Value of word is: " << word << endl
13         << "Value of static_cast< const void * >( word ) is: "
14         << static_cast< const void * >( word ) << endl;
15   } // end main


Value of word is: again
Value of static_cast< const void * >( word ) is: 0135CC70


Fig. 13.3. Printing the address stored in a char * variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.205.165