Cannot figure out why I'm getting an error

This is supposed to prompt the user to enter sales for each month and then calculate yearly totals, then finally a total sales figure. I have only done the first year calculation but after the program runs it calculates year one sales then crashes saying:

program terminated with status -1073741819

debugger gives me an error on line 47 which is the return 0; line. I'm not sure what is wrong. Any help would be awesome.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>

using namespace std;

const int NumberOfMonths = 12;


int main()
{
    string months[NumberOfMonths] =
    {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    };

    int MonthlySales[12][3];

    int sales = 0;

    for (int year = 1; year <= 3; ++year)
    {
        for (int i = 0; i < 12; ++i)
        {
            cout << "\nEnter sales for " << months[i] << ": ";
            cin >> sales;
            MonthlySales[i][year] = sales;
        }
    }

    int YearOneSales = 0;
    for (int j = 0; j < 12; ++j)
        YearOneSales += MonthlySales[j][1];

    cout << "\nTotal sales for year 1 were: " << YearOneSales << endl;

    return 0;
}
You're stepping out of bounds of your array.

Remember that arrays are ranged from [0,X)... not [1,X] This means that if you have an array of size [3], valid indexes are [0], [1], and [2]. Index [3] is out of bounds.

Lin 31:

 
for (int year = 1; year <= 3; ++year)

This means you'll be using indexes 1, 2, and 3.. which is wrong. You probably want to change this to the below:

 
for (int year = 0; year < 3; ++year)

Note you start at ZERO (not at 1), and you loop while you're LESS THAN (not <=) three.

Similar problem on line 43:
 
        YearOneSales += MonthlySales[j][1];


While this isn't "wrong" in the same sense that the above code was... it's probably not what you wanted. You probably wanted year [0] here... not year [1].
Last edited on
When you try to access MonthlySales[i][year] on the third iteration of your year loop, you're trying to access an array index that's out of bounds.

Replace:
for( int year = 1; year <= 3; ++year )
With:
for( int year = 0; year < 3; ++year )

Edit: Damn it, Disch. One minute sooner? Really?
Last edited on
Thanks to both of you. That should have been obvious, but we learn from mistakes :)

Topic archived. No new replies allowed.