This code…
#include <iostream>
int main(int argc, char * argv[])
{
char c = 'A';
std::cout << &c;
return 0;
}
…correctly outputs “A” both in Eclipse debug mode and on the command line.
However when I modify the code to…
#include <iostream>
int main(int argc, char * argv[])
{
char c = 'A';
bool b = true;
std::cout << &c;
return 0;
}
…it outputs “A␁” (the latin letter ‘A’ followed by the ‘start of header’ ASCII control character) in Eclipse debug mode and on the Windows 7 command line. Incidentally, when using bool b = false instead I don’t get the ␁ character.
I know ␀ has the value 0, and ␁ has the value 1, but why is cout << &c affected by the bool? Can anyone explain why this is?
Edit: forgot to add my environment: Windows 7 64-bit, MinGW with g++ 4.5.2, in Eclipse Indigo
In the first version you are getting (un)lucky.
In the second one you are getting (un)lucky (that it does not crash) but it prints more garbage.
When you use & on a char object you get a char*. When you try and stream a char* it acts differently to all other pointers (which normally prints the address). But a char* is assumed to be a C-String. A C-String is a sequence of bytes terminated by a null character ‘\0’;
What is actually happening is that it is printing every memory location (treating it as a char) starting at the variable ‘c’ and moving through memory until it finds the character ‘\0’
Example 1 above:
In your case you are lucky there happens to be a null character lying around in memory just after the variable ‘c’.
Example 2 above:
In your case you are lucky there happens to be a null character lying around in memory just after the variable ‘b’. But the variable ‘b’ is also be interpreted.
What you actually wanted to do was:
Or you could have created a string:
Or to get the address