C++ 为什么 cout 打印 char 数组与其他数组不同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/501816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does cout print char arrays differently from other arrays?
提问by Luca Matteis
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.
我正在使用 C++ 来理解指针的工作原理。我有一段使用数组的代码,我使用它只是为了了解等效项如何与指针一起使用。
int main() {
int arr[10] = {1,2,3};
char arr2[10] = {'c','i','a','o','cout << static_cast<const void*>(arr2) << endl;
'};
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".
但是,当我运行它时,arr
输出整数数组的第一个元素的地址(如预期),但arr2
不输出字符数组的第一个元素的地址;它实际上打印“ciao”。
What is it that I'm missing or that I haven't learned yet about this?
我遗漏了什么或我还没有学到什么?
回答by Johannes Schaub - litb
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<<:
重载了 forconst void*
和 for的是运算符<< const char*
。您的 char 数组被转换const char*
并传递给该重载,因为它比 to 更适合const void*
。然而,int 数组被转换const void*
并传递给那个版本。operator<< 的版本const void*
只输出地址。采用 的版本const char*
实际上将其视为 C 字符串并输出每个字符,直到终止的空字符。如果您不希望那样,请在将字符数组const void*
传递给 operator<< 时将其显式转换为:
cout << &arr2 << endl;
回答by crashmstr
Because cout's operator <<
is overloaded for char*
to output strings, and arr2
matches that.
因为 cout'soperator <<
被重载char*
以输出字符串,并arr2
匹配它。
If you want the address, try casting the character array as a void pointer.
如果需要地址,请尝试将字符数组转换为空指针。
回答by Darron
There is a standard overload for char* that outputs a NUL terminated string.
char* 有一个标准重载,它输出一个 NUL 终止的字符串。
回答by Mystic
While casting is probably a more meaningful approach, you could also use the addressof operator:
虽然强制转换可能是一种更有意义的方法,但您也可以使用 addressof 运算符:
##代码##