c++coutoperation

why cout &char operation same expresion not return the same answer


#include "iostream"

using namespace std;

int main() {
    char c = 'x';
    cout << &c << endl;
}

cout << &c << endlprint 'x'

2.

#include "iostream"

using namespace std;

int main() {
    int x = 222222;
    char c = 'x';
    cout << &c << endl;
    cout << x << endl;
}

cout << &c << endl;print 'xd',seems the adress of the variable

os version

Linux vm 5.19.0-45-generic #46-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 09:08:58 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

gcc version

gcc version 12.2.0 (Ubuntu 12.2.0-3ubuntu1)

the expression are the same ,why cout different?


Solution

  • You're reading out of bounds of c and therefore your program's behavior is undefined.

    When a char* is passed to std::cout's << operator, it treats that pointer as a c-style nul-terminated string. That means it will keep reading characters from successive bytes starting at the byte pointed to by the pointer until it finds a nul (0) byte.

    But a single char isn't nul-terminated, so cout will try to read data from after the char object, resulting in undefined behavior. In practice it will end up wandering into the bytes that represent the int 222222 and interpreting them as characters. Eventually it will find a nul byte and stop (hopefully before it wanders out of your process's currently mapped address space and crashes).