Reputation: 47
#include "iostream"
using namespace std;
int main() {
char c = 'x';
cout << &c << endl;
}
cout << &c << endl
print '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?
Upvotes: 2
Views: 91
Reputation: 30569
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).
Upvotes: 4
Reputation: 117318
The problem with this
char c = 'x';
cout << &c << endl;
is that, since &c
is a char*
, it will use this operator<<
:
template< class Traits >
basic_ostream<char, Traits>&
operator<<( basic_ostream<char, Traits>& os, const char* s );
That function will use std::char_traits<char>::length(reinterpret_cast<const char*>(s))
to figure out how many characters to insert into the stream. That function in turn
s
, that is, the position of the terminating null character.Since you only have a single char
(which is not \0
), the length
function will read whatever lies after x
in memory. This has undefined behavior, so it could crash or find a \0
somewhere and insert a lot of garbage into the stream.
If you want to print its address, cast to a void*
:
std::cout << static_cast<void*>(&c) << '\n';
Upvotes: 4