以下代码为前两个 for 语句正确输出数组元素,但在第三个 for 语句中,它在使用 cout 时错误地从基于范围的 for 循环输出数组元素(在第一个中使用 printf)。这是为什么?
#include <iostream>
using namespace std;
int main( int argc, char ** argv )
{
int myArray[]={10,20,30,40,50};
for (int i : myArray) {
printf("%d\n", i);
}
for (int i = 0 ; i < 5; i++) {
cout << myArray[i] << endl;
}
for (int i : myArray) {
cout << myArray[i] << endl;
}
return 0;
}
输出:
10
20
30
40
50
10
20
30
40
50
-1707465271
0
1606417258
1606417820
1606418039
最佳答案
您有越界访问
for (int i : myArray) {
cout << myArray[i] << endl;
}
作为 i
将是 10,20,30,40,50。
你想要
for (int i : myArray) {
cout << i << endl;
}
就像您使用 printf
一样。
关于c++ - 基于范围的 for 循环使用 cout 错误地输出数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30539331/