Why is address of char data not displayed?

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

    hrnt is right about the reason for the blank: &b has type char*, and so gets printed as a string until the first zero byte. Presumably b is 0. If you set b to, say, 'A', then you should expect the printout to be a string starting with 'A' and continuing with garbage until the next zero byte. Use static_cast(&b) to print it as a an address.

    For your second question, &c - &i is 8, because the size of an int is 4, the char is 1, and the string starts at the next 8-byte boundary (you are probably on a 64-bit system). Each type has a particular alignment, and C++ aligns the fields in the struct according to it, adding padding appropriately. (The rule of thumb is that a primitive field of size N is aligned to a multiple of N.) In particular you can add 3 more char fields after b without affecting the address &c.

提交回复
热议问题