Why is address of char data not displayed?

前端 未结 8 1226
执念已碎
执念已碎 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:46

    For the second issue - the compiler by default will pad structure members. The default pad is to the sizeof(int), 4 bytes (on most architectures). This is why an int followed by a char will take 8 bytes in the structure, so the string member is at offset 8.

    To disable padding, use #pragma pack(x), where x is the pad size in bytes.

    0 讨论(0)
  • 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<void *>(&b) << endl;
    
    0 讨论(0)
提交回复
热议问题