I wonder why
Since the thread insertion operator requires that any character pointer passed to it point to a character string with a null terminating character. The pointer passed to cout
points to A
, which is not a null-terminated character string. Because the preconditions (requirements) of the operation were not met, the behavior is undefined.
There are two relevant overloads for the insert operator (I simplified the details of the template and the fact that one of them is member overload and the other is not):
ostream& operator<< (const void*); ostream& operator<< (const char*);
All other pointers are implicitly converted to void*
and use the same overload, and the pointer is displayed as a memory address. But the latter prefers overloading for character pointers, and the argument should be an empty terminating string.
So, since a character pointer is interpreted as a null-terminated string, a naive attempt to print the address of a character does not work. Solution: direct pointer to void*
before passing to stream.
Streams were designed to conveniently support null-terminated strings, such as string literals, which were considered (and) streams more typically than addresses. For example, it is convenient that std::cout << "Hello World!";
. Prints "Hello World" instead of the memory address where the string literal is located.
source share