0

what if we increase the value of x in for loop while working with array

for example this is the program: #include <iostream> using namespace std; int main(){ int myArr[5]; for(int x=0; x<=4; x++) { myArr[x] = 42; cout << x << ": " << myArr[x] << endl; } return 0; } which gives an output: 0: 42 1: 42 2: 42 3: 42 4: 42 but if change x<6 in for loop it gives output: 0: 42 1: 42 2: 42 3: 42 4: 42 42: -2045 please explain this -2045

11th Jun 2017, 6:21 PM
Manish Kumar
Manish Kumar - avatar
2 odpowiedzi
+ 3
This is an error. You are telling the compiler to go beyond the allocated memory space for myArr. Since myArr only allocates memory for five integers, by saying myArr[5], you are making an error. You should adjust your loops to account for the size of your array. In this case, it should look like this: int myArr[5]; int arrSize = sizeof(myArr)/sizeof(int); for (int i = 0; i < arrSize; i++) { myArr[i] = 42; cout << i << ": " << myArr[i] << endl; } Or you can use a for-each loop: int x = 0; for (auto i : myArr) { i = 42; cout << x++ << ": " << i << endl; }
11th Jun 2017, 6:45 PM
Zeke Williams
Zeke Williams - avatar
+ 1
you are accessing the memory area which falls outside of the array boundry. The size of your array is 5 but with i < 6, you are trying to read the value at location myArr[5], can contain garbage data or valid data of other programs running on your system. In current case, the value @ location myArr[5] is -2045 and that is what is printed.
11th Jun 2017, 7:01 PM
NeutronStar
NeutronStar - avatar