Unexpected results when printing array and char to screen with cout(使用 cout 将数组和字符打印到屏幕时出现意外结果)
问题描述
作为一个学习 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
我的问题是:
为什么下面会输出字符串'0xbfd66a88'?我期待它返回数组中第一个元素的地址:
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)调用二进制 +
时,编译器会提升您的char
为 signed int
或 unsigned 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;
请参阅这个问题.
这篇关于使用 cout 将数组和字符打印到屏幕时出现意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 cout 将数组和字符打印到屏幕时出现意外结果


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01