Simple array question

Hi, as part of my computer science homework I have to edit this program so that it works as you'd expect.

Originally there were 3 errors I was tasked to fix, however, when I run it I can enter the 6 values and it produces an average correctly but immediately after I get a error -

'C++ Runtime Library' error stating 'Stack around the variable 'pollution_level' was corrupted'.

I feel as though I've missed something but I can't quite see what it is.

Any help would be greatly appreciated =) Thank you in advance.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
	int pollution_level[6];
	double average = 0;
	int counter =1;

	while (counter<=6)
	{
		cout<<"Enter pollution level for day "<<counter<<" range (1-100): ";
		cin>>pollution_level[counter];
		average = average + pollution_level[counter];
		counter++;
	}
	cout<<endl;
	cout<< "The average pollution level over those 6 days was :"<<average/6<<endl;

	return 0;
}
Your while loop is subscripting past the end of the array. You declared the array to have 6 entries. Those entries are [0] to [5]. Your loop is looking at entries [1] to [6].
Ah that makes sense. I seemed to have fixed it this way but I'm not sure if its really the most 'elegant' way to do it: -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
	int pollution_level[6];
	double average = 0;
	int counter = 1;

	while (counter<=6)
	{
		cout<<"Enter pollution level for day "<<counter<<" range (1-100): ";
		cin>>pollution_level[counter-1];
		average = average + pollution_level[counter-1];
		counter++;
	}
	cout<<endl;
	cout<< "The average pollution level over those 6 days was :"<<average/6<<endl;

	return 0;
}
You could just initialize counter to 0 and run the while up to <6.


edit: or to remove the tie to a specific number, you could have a separate variable for array size and use that instead of hardcoding 6.
Last edited on
I tried that originally but then the cout showed as :-

"Enter pollution level for day 0"

instead of

"Enter pollution level for day 1".
Last edited on
I think I'd tend to do this to compensate for the difference and keep the counter running the actual values of the array.

cout<<"Enter pollution level for day "<<counter+1<<" range (1-100): ";

But either way will work.
Yeah that really does seem like the better way of doing it.

Thanks very much for your help guys, I appreciate it =)


Have a pleasant day.
I seemed to have fixed it this way but I'm not sure if its really the most 'elegant' way to do it:


Your fix will work, but it is better to think in the standard C/C++ idiom of arrays, vectors and such as indexed from 0 to n-1. Subtracting 1 from the subscript everytime you reference the array is prone to errors (as you discovered).

Topic archived. No new replies allowed.