What is the difference between int and char arrays below:
int main()
{
int numbers[] = {2,1,3};
char letter[] = {'a','b','\0'};
cout<< numbers<<endl;
cout<< letter<<endl;
}
Output:
0x22ff12 // an address
ab
Why isn’t the 213 displayed ?
I know the name of an array will point to the address of its first element, but why
does a char array display different behavior?
There is no
operator<<overload that takes arrays, exactly, so the arguments you pass (egnumbersandletter) undergo array-to-pointer conversion, tovoid*andchar*respectively.There is an overload of
operator<<()that takes aconst void*, and another that takes aconst char*. When you call:the
const void*version is matched, but when you call:the
const char*version is matched.In the
const void*version, the pointer is displayed, while with theconst char*version, the string is displayed up to the null terminator.