Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

C++ array out-of-bounds crash

+9 votes
asked Feb 18 by gta6isnotfree (430 points)

Hey, I’m trying to make an array sum in C++ but my program crashes:

#include 
using namespace std;

int main() {
    int arr[5];
    for (int i = 0; i 

Why does it crash when I print “Done”? Any fix?

2 Answers

+1 vote
answered Feb 18 by Peter Minarik (101,340 points)

Please, share the entire code.

You're probably indexing out of array. Your loop should look like

for (int i = 0; i < 5; i++)

i.e., stop before reaching index 5. You have 5 elements: 0, 1, 2, 3, 4; there's no element indexed with 5 (as it would be the 6th element).

0 votes
answered Mar 18 by Tanmay Awad (140 points)
#include<iostream>
using namespace std;

int main() {
    int arr[5];
    for (int i = 0; i<5;i++){
int sum=int sum + arr[i];}
cout<<"sum of the arry is"<<sum<<endl;
return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...