Why is address of char data not displayed?

前端 未结 8 1315
执念已碎
执念已碎 2020-11-22 10:02
class Address {
      int i ;
      char b;
      string c;
      public:
           void showMap ( void ) ;
};

void Address :: showMap ( void ) {
            cout          


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 10:47

    When you are taking the address of b, you get char *. operator<< interprets that as a C string, and tries to print a character sequence instead of its address.

    try cout << "address of char :" << (void *) &b << endl instead.

    [EDIT] Like Tomek commented, a more proper cast to use in this case is static_cast, which is a safer alternative. Here is a version that uses it instead of the C-style cast:

    cout << "address of char   :" << static_cast(&b) << endl;
    

提交回复
热议问题