Why is address of char data not displayed?

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

    When you stream the address of a char to an ostream, it interprets that as being the address of the first character of an ASCIIZ "C-style" string, and tries to print the presumed string. You don't have a NUL terminator, so the output will keep trying to read from memory until it happens to find one or the OS shuts it down for trying to read from an invalid address. All the garbage it scans over will be sent to your output.

    You can probably get it to display the address you want by casting it, as in (void*)&b.

    Re the offsets into the structure: you observed the string is placed at offset 8. This is probably because you have 32-bit ints, then an 8-bit char, then the compiler chooses to insert 3 more 8-bit chars so that the string object will be aligned at a 32-bit word boundary. Many CPUs/memory-architectures need pointers, ints etc. to be on word-size boundaries to perform efficient operations on them, and would otherwise have to do many more operations to read and combine multiple values from memory before being able to use the values in an operation. Depending on your system, it may be that every class object needs to start on a word boundary, or it may be that std::string in particular starts with a size_t, pointer or other type that requires such alignment.

提交回复
热议问题