Why is address of char data not displayed?

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

    There are 2 questions:

    • Why it does not print the address for the char:

    Printing pointers will print the address for the int*and the string* but will not print the contents for char* as there is a special overload in operator<<. If you want the address then use: static_cast(&c);

    • Why the address difference between the int and the string is 8

    On your platform sizeof(int) is 4 and sizeof(char) is 1 so you really should ask why 8 not 5. The reason is that string is aligned on a 4-byte boundary. Machines work with words rather than bytes, and work faster if words are not therefore "split" a few bytes here and a few bytes there. This is called alignment

    Your system probably aligns to 4-byte boundaries. If you had a 64-bit system with 64-bit integers the difference would be 16.

    (Note: 64-bit system generally refers to the size of a pointer, not an int. So a 64-bit system with a 4-byte int would still have a difference of 8 as 4+1 = 5 but rounds up to 8. If sizeof(int) is 8 then 8+1 = 9 but this rounds up to 16)

提交回复
热议问题