Consider the following code snippet:
class Address { int i ; char b; string c; public: void showMap ( void ) ; }; void Address :: showMap ( void ) { cout << "address of int :" << &i << endl ; cout << "address of char :" << &b << endl ; cout << "address of string :" << &c << endl ; }
Expectedly, the output should display the addresses of the int, char, and string member variables. However, the address of the char variable b remains blank.
This oddity arises because the << operator interprets &b as a C-style string rather than an address. Char pointers are interpreted as null-terminated character sequences by the << operator.
To resolve this issue and display the address of the char variable, you can use the following modified code:
cout << "address of char :" << (void *) &b << endl;
Here, we use a C-style cast to explicitly convert &b to a void *. This instructs the << operator to treat it as an address rather than a character sequence. A safer alternative is to use static_cast:
cout << "address of char :" << static_cast<void *>(&b) << endl;
When the int, char, and string member variables are declared as public, the output changes slightly:
... int : something ... char : ... string : something_2
Here, something_2 is always 8 less than something.
This difference occurs because the compiler pads the public member variables to align them optimally for memory access. In this case, the char variable is likely padded to 8 bytes, resulting in an 8-byte difference in addresses between the int and string variables.
The above is the detailed content of Why Doesn't `cout` Display the Address of a `char` Member Variable Correctly?. For more information, please follow other related articles on the PHP Chinese website!