简体   繁体   English

为什么 cout 打印 char 数组与其他数组不同?

[英]Why does cout print char arrays differently from other arrays?

I'm using C++ to understand how exactly pointers work.我正在使用 C++ 来理解指针的工作原理。 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;但是,当我运行它时, arr输出整数数组的第一个元素的地址(如预期),但arr2不输出字符数组的第一个元素的地址; it actually prints "ciao".它实际上打印“ciao”。

What is it that I'm missing or that I haven't learned yet about this?我遗漏了什么或我还没有学到什么?

It's the operator<< that is overloaded for const void* and for const char* .对于const void*const char*重载的是运算符<<。 Your char array is converted to const char* and passed to that overload, because it fits better than to const void* .您的 char 数组被转换为const char*并传递给该重载,因为它比const void*更适合。 The int array, however, is converted to const void* and passed to that version.但是,int 数组被转换为const void*并传递给该版本。 The version of operator<< taking const void* just outputs the address. operator<< 采用const void*的版本只输出地址。 The version taking the const char* actually treats it like a C-string and outputs every character until the terminating null character.采用const char*的版本实际上将其视为 C 字符串并输出每个字符,直到终止的空字符。 If you don't want that, convert your char array to const void* explicitly when passing it to operator<<:如果您不希望那样,请在将 char 数组传递给 operator<< 时将其显式转换为const void*

cout << static_cast<const void*>(arr2) << endl;

Because cout's operator << is overloaded for char* to output strings, and arr2 matches that.因为 cout 的operator <<char*重载以输出字符串,而arr2匹配。

If you want the address, try casting the character array as a void pointer.如果需要地址,请尝试将字符数组转换为空指针。

char* 有一个标准重载,它输出一个 NUL 终止的字符串。

虽然强制转换可能是一种更有意义的方法,但您也可以使用 addressof 运算符:

cout << &arr2 << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM