Cast a as a void* to avoid std::iostream::operator<<(const char*) being called:
#include<iostream>
int main()
{
char a[]={'0','1','2','3','4','5','6'};
std::cout << static_cast<void*>(a) << std::endl;
}
Please explain me this strange output for char array.
std::iostream::operator<<() exist for various argument types, each one is handled differently:
std::iostream::operator<<(const char*) prints a C-style string, this is what is called when you write std::cout << p.
std::iostream::operator<<(const void*) prints a pointer as an hexadecimal integer, this is what is called when you write std::cout << static_cast<void*>(a).
I had used a integer array which gives me a simple hexadecimal address as output.
If you'd declare an array of integers, printing it wouldn't call the const char* version but the const int* version if it existed. Since it's not defined, the compiler defaults to the const void* since a pointer can be implicitly cast to a const void*:
#include<iostream>
int main()
{
int a[]={'0','1','2','3','4','5','6'};
const int* p = a;
std::cout << p << std::endl; // prints address of a.
}
a, you're printingaas if it was a C, NUL-terminated string, which is not.C, and inherited byC++, an array ofchar(or pointer tochar) is treated as a textual string in a lot of contexts. It has to be terminated with0, or "NUL" character, denoted as acharby'\0'. Which in this case, it isn't, which is why you see some garbage at the end, it just keeps printing until it happens to hit a byte containing0.