为什么 cout 打印 char 数组与其他数组不同? [英] Why does cout print char arrays differently from other arrays?

查看:26
本文介绍了为什么 cout 打印 char 数组与其他数组不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C++ 来理解指针的工作原理.我有一段使用数组的代码,我使用它只是为了了解等效项如何与指针一起使用.

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;
}

但是,当我运行它时,arr 输出整数数组的第一个元素的地址(如预期),但 arr2 不输出整数数组的地址字符数组的第一个元素;它实际上打印了ciao".

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?

推荐答案

是操作符<<<为 const void*const char* 重载.您的 char 数组被转换为 const char* 并传递给该重载,因为它比 const void* 更适合.但是,int 数组被转换为 const void* 并传递给那个版本.运算符<<的版本取 const void* 只是输出地址.采用 const char* 的版本实际上将其视为 C 字符串并输出每个字符,直到终止的空字符.如果您不希望那样,请在将字符数组传递给 operator<<:

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;

这篇关于为什么 cout 打印 char 数组与其他数组不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆