-
array exercises
I am doing some array exercises and I keep getting this debug error. Can anybody please give me any ideas on what this means? The program compiles and outputs the array total, as it should.
Here's the code:
Code:
//array initialization and sum output
#include <iostream>
using namespace std;
int main ()
{
int i = 0, sum[6];
int values[6] = {10,22,13,99,4,5};
for (i = 0; i < 6; i++ )
{
cout << values[i] << " " ;
}
sum[i] = values[0] + values[1] + values[2] + values[3] + values[4] + values[5];
cout << endl;
cout << "Total is: ";
cout << sum[i] << endl;
}
Code:
array2.exe has triggered a breakpoint
The program '[2924] array2.exe: Native' has exited with code 0 (0x0).
It also gives an error of runtime check failure #2 - stack around the variable 'sum' was corrupted.
Any ideas would be great... Thanks!
-
You only need one sum, not an array of them. As it is, when the loop ends i is 6, so you walk off the end of the array.
-
Code:
> sum[i] = values[0] + values[1] + values[2] + values[3] + values[4] + values[5];
Here i has the value 6 (because it's past the for-loop), and is outside the bounds of the array sum. sum really doesn't need to be an array, as all you store is one value. So you could change your code to:
Code:
//array initialization and sum output
#include <iostream>
using namespace std;
int main ()
{
int i = 0;
int values[6] = {10,22,13,99,4,5};
int sum = 0;
for (i = 0; i < 6; i++ )
{
cout << values[i] << " " ;
sum += values[i];
}
cout << endl;
cout << "Total is: " << sum << endl;
}
-
Oh, yes.. I kind of missed that small detail, :).. Thanks guys..