So i was reading the learncpp tutorial, and i was trying to print the address of a char pointer, because when you do :
char c{'i'};
cout << &c << endl;
It will just print the string "i", because i guess the compiler identify a char pointer to a char array, which is a string (however i don't understand why it's just printing "i", because there is not '\0' after the character 'i').
Anyway, i then tried to static_cast the char pointer into an int pointer so that is will print the address :
char c{'i'};
cout << static_cast<int*>(&c) << endl;
But this doesn't even compile, i have an error "invalid static_cast from the type << char* >> to the type << int* >>".
Finally, i simply tried a C-type cast like this :
char c{'i'};
cout << (int*)(&c) << endl;
And it works, it prints an address.
So my questions are :
Thanks
Firstly, the static_cast<int*>(&c)
will fail because static_cast
only allows a very specific subset of type conversions. For instance, you can static_cast
between numeric types, or between two class types which are related by inheritance (i.e. one inherits the other at some point in the inheritance hierarchy).
What you're doing is simply trying to "reinterpret" the address as an address to a different type. The reason being that C++ std::ostream
overloads operator<<
for const char*
. If you only want to print the address itself, standard convention is to convert to void*
via static_cast<void*>(&c)
or just (void*)&c
if you're ok with C-style casts. void*
is basically a pointer with no type information, which makes it perfect if all you want to do is print out the value of the address itself.
The reason the C-style case compiles is because a C-style cast employs very ... shall we say risky ... methods to perform the conversion. It's allowed to perform const_cast
, reinterpret_cast
, and static_cast
- whatever is necessary - in order to perform the cast you specified. This behavior is detailed on cppreference.com.
As for why the example of printing the char*
directly only prints a single character despite not being terminated: undefined behavior is undefined. Apparently, it just so happens that (with this compiler) the executable happens to have a zero (null) byte immediately following it, wherever it may be. The compiler might even realize you assign a value but never modify it, so it might not even be in the stack (it might be in the data
segment of the executable). The moral of the story is just not to invoke undefined behavior.