使用 cout 将数组和字符打印到屏幕时出现意外结果

2022-01-12 00:00:00 string arrays char c++

作为一个学习 C++ 的初学者,我试图理解 char 类型的数组和 int 类型的数组之间的区别.这是我的代码:

As a beginner of learning C++, I am trying to understand the difference between an array of type char and an array of type int. Here is my code:

void IntArray () {
    int array[5] = {5,6,7,8,9};

    cout << "Print int array: " << array << endl;
    cout << "Print int array[0]: " << array[0] << endl;
    cout << "Print int array[0]+1: " << array[0]+1 << endl;
}

void CharArray () {
    char array[5] = {'a', 'b', 'c', 'd', ''};

    cout << "Print char array: " << array << endl;
    cout << "Print char array[0]: " << array[0] << endl;
    cout << "Print char array[0]+1: " << array[0]+1 << endl;
}

这是输出:

Print int array: 0xbfd66a88
Print int array[0]: 5
Print int array[0]+1: 6
Print char array: abcd
Print char array[0]: a
Print char array[0]+1: 98

我的问题是:

  1. 为什么下面会输出字符串'0xbfd66a88'?我期待它返回数组中第一个元素的地址:

  1. Why does the following output the string '0xbfd66a88'? I was expecting it to return the address of the first element in the array:

cout << "Print char array: " << array << endl;

  • 为什么下面的输出是'98'?我期待它输出字母'b':

  • Why does the following output '98'? I was expecting it to output the letter 'b':

    cout << "Print char array[0]+1: " << array[0]+1 << endl;
    

  • 推荐答案

    1.

    因为当您将 char 数组流式传输到 cout 时,它们的处理方式与其他数组不同 - << 运算符为 <代码>const char*.这是为了与 C 兼容,因此以 null 结尾的 char 数组被视为字符串.

    1.

    Because char arrays are treated differently to other arrays when you stream them to cout - the << operator is overloaded for const char*. This is for compatibility with C, so that null-terminated char arrays are treated as strings.

    请参阅这个问题.

    这是由于整体推广.当您使用 char(值为 'a')和 int(值为 1)调用二进制 + 时,编译器会提升您的charsigned intunsigned int.哪一个是特定于实现的――它取决于默认情况下 char 是有符号还是无符号,以及哪个 int 可以采用 char 的全部范围.因此,+ 操作符被调用时使用值 '97' 和 '1',它返回值 '98'.要将其打印为 char,您需要先转换它:

    This is due to integral promotion. When you call the binary + with a char (with value 'a') and an int (with value 1), the compiler promotes your char to either a signed int or an unsigned int. Which one is implementation specific - it depends on whether char is signed or unsigned by default, and which int can take the full range of char. So, the + operator is called with the values '97' and '1', and it returns the value '98'. To print that as a char, you need to first cast it:

    cout << "Print char array[0]+1: " << static_cast<char>(array[0]+1) << endl;
    

    请参阅这个问题.

    相关文章