使用cout将数组和char打印到屏幕上时出现意外结果 [英] Unexpected results when printing array and char to screen with 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', '\0'};
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兼容,因此将以空终止的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将数组和char打印到屏幕上时出现意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!