Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cout print char arrays differently from other arrays?

I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers.

int main() {    
    int arr[10] = {1,2,3};    
    char arr2[10] = {'c','i','a','o','\0'};
    cout << arr << endl;
    cout << arr2 << endl;
}

However when I run this, arr outputs the address of the first element of the array of ints (as expected) but arr2 doesn't output the address of the first element of the array of chars; it actually prints "ciao".

What is it that I'm missing or that I haven't learned yet about this?

like image 428
Luca Matteis Avatar asked Feb 01 '09 23:02

Luca Matteis


People also ask

Which is faster string or char array?

So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.

Which is better string or char array?

C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.

Can you compare char arrays in C?

The strcmp() function is a built-in library function in the C language. Its basic role is to compare two character arrays or strings terminated by null value (C-strings) lexicographically. The strcmp() function is called using two character arrays as parameters and returns an integer value.


2 Answers

It's the operator<< that is overloaded for const void* and for const char*. Your char array is converted to const char* and passed to that overload, because it fits better than to const void*. The int array, however, is converted to const void* and passed to that version. The version of operator<< taking const void* just outputs the address. The version taking the const char* actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array to const void* explicitly when passing it to operator<<:

cout << static_cast<const void*>(arr2) << endl;
like image 76
Johannes Schaub - litb Avatar answered Oct 29 '22 13:10

Johannes Schaub - litb


Because cout's operator << is overloaded for char* to output strings, and arr2 matches that.

If you want the address, try casting the character array as a void pointer.

like image 23
crashmstr Avatar answered Oct 29 '22 13:10

crashmstr