codeblocks program stopped working

Hi, here's my program. It is to reverse a float array using function. I'm just learning c++
programming now(high school).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    #include <iostream>
    using namespace std;

    float rev(float a[]);

    int main() {
    float ar[5];
    int i;
    cout << "Enter a float array having 5 elements.\n";
    for (i = 0; i <= 5; i++) {
        cin >> ar[i];}
    rev(ar);
    cout << "The reversed array is:\n" << ar[i];
    cin.get();
    return 0;
    }

    float rev(float a[]) {
        float temp;
        int len = 5, i;
        for (i = 0; i <= 5; i++) {
            temp = a[i];
            a[len] = a[i];
            a[i] = temp;
        }
        return (a[i]);
    }

Here's what happens while executing the program:

1
2
3
 Enter a float array having 5 elements.
    1.0 2.0 3.0 4.0 5.0 6.0
    

when I press enter , it says 'filename.cpp' has stopped working. windows is checking for solutions and then in the program window it says

Process returned -1073741819(0xC0000005) execution time.......
Why and when does this error occur and how do I correct it ?


i <= 5 should be i < 5.
When does it happen? I'm assuming it's when your function gets called. You're accessing memory outside your array. Index 5 is outside of it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

float rev(float a[]);

int main() {
    float ar[5];
    int i;
    cout << "Enter a float array having 5 elements.\n";
    for (i = 0; i < 5; i++) {
        cin >> ar[i];}
    rev(ar);
    cout << "The reversed array is:\n" << ar[i];
    cin.get();
    return 0;
    }

    float rev(float a[]) {
        float temp;
        int len = 5, i;
        for (i = 0; i < 5; i++) {
            temp = a[i];
            a[len] = a[i];
            a[i] = temp;
        }
        return (a[i]);
    }
 


Topic archived. No new replies allowed.