+ 1

What’s wrong?

#include <iostream> using namespace std; int main() { int a=1; a+=1; int dog[]={a}; int sum=0; for (int x=0;x<5;x++){ sum +=dog[x]; cout <<sum<<endl; } return 0; }

20th Apr 2019, 1:44 PM
GUUKMER_plays
GUUKMER_plays - avatar
2 Respostas
+ 2
This code suffers from a run time error typically referred to as an "array index out of bounds exception". This occurs when you attempt to access an index in an array outside of that array's allocated memory space. This creates an error because it causes the user to access unallocated memory, which could cause undefined behavior. When you wrote the line: int dog[] = {a}; You created an array of int's with length one, where the one element is initialized to the value of "a". Since dog is an array of length 1, you can only access dog[0]. Trying to access another index in the array, like dog[101] or dog[-4] will result in an error. This occurs inside the for-loop: for(int x=0;x<5;x++) { sum +=dog[x]; ... } Here, you use the for-loop to increment "x" from 0 to 4 (stopping when x = 5). The first time you call "sum += dog[x]", it works, because x = 0, and we are allowed to access dog[0]. But the next time, x = 1, so we try to access dog[1]. This is what causes the error. To fix this, I would suggest changing the for-loop like this: for(x = 0; x < 1; ++x) { ... } Or, better yet, you could use another int variable "length" to represent the length of the dog array: for(x = 0; x < length; ++x) { ... } Hope this helped!
20th Apr 2019, 3:46 PM
Jack McCarthy
Jack McCarthy - avatar
+ 2
You don't assign values to dog[0] - dog[4]. It adds whatever is coincidentally in memory.
20th Apr 2019, 3:49 PM
Paul
Paul - avatar