In foreach
loop, it seems the first element is not traversed and the 6th element num[5]
is traversed which is undefined.
#include<iostream>
using namespace std;
int num[5];
int main() {
for (int i = 0; i < 5; i++) num[i] = i + 1;
for (auto i : num) cout << num[i] << " ";
return 0;
}
expected output: 1,2,3,4,5
output: 2,3,4,5,0
Because i
is not an index, but the value, you should replace:
for (auto i:num)cout<<num[i]<<" ";
with
for (auto i:num)cout<< i <<" ";
Then you get the proper output 1 2 3 4 5
for (int i=0;i<5;i++)num[i]=i+1;
Loads the num
variable like [0] = 1
, [1] = 2
... [4] = 5
for (auto i:num)cout<<num[i]<<" ";
This actually goes through the values in num
, not the indexes, so what you have here is printing num[1]
, num[2]
... num[5]
( num[5]
is undefined behavior by the way)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.