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.
}