为什么从其他阵列清点打印字符数组不同? [英] Why does cout print char arrays differently from other arrays?
问题描述
我用C ++来理解指针究竟如何工作。我有这块code的使用数组,我只用它来了解相当于是如何工作的指针。
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;
}
然而,当我运行此,改编
输出整型数组的第一个元素的地址(如预期),但 ARR2
做的字符数组的第一个元素的不输出的地址;它实际上打印侨。
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?
推荐答案
这是运营商LT;&LT;即重载常量无效*
和为const char *
。您的字符数组转换为为const char *
,并传递给超载,因为它适合比常量无效*更好
。在int数组,但是,被转换为常量无效*
并传递到该版本。运营商所述的版本;&下;服用常量无效*
只是输出的地址。该版本服用为const char *
其实把它像一个C-字符串,每个字符,直到终止空字符输出。如果你不希望这样,你的字符数组转换为常量无效*
明确传递给运营商的LT时;&LT;
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;
这篇关于为什么从其他阵列清点打印字符数组不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!