#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?
3
Answers
if you are trying to store the address of x in c, this would be right way to do that:
now if you want to use the address to retreive the value of x then this line will do that:
cout << *c << endl; //prints value stored in the address c is pointing at which is value of x
Hope this helps to understand the concept.
The problem with this
is that, since
&c
is achar*
, it will use thisoperator<<
: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 turns
, that is, the position of the terminating null character.Since you only have a single
char
(which is not