I have long been declaring a lot more space for arrays during competitive programming.
int pr[100010]; //for example
However, when I was trying to declare an array for a smaller space this morning, things went wrong.
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[100]; //seems enough
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
You see, this program was for calculating the prefix sum of an array. The value for this array comes from input. The space for this array seems enough. But when I input these to my program and found that it occurs to a wrong output:
//the input:
5
1 2 3 4 5
//the output:
1875947561
1875947563
1875947566
1875947570
1875947575
The array might just out of bounds. I thought.
However, when I modified the space 100
to 10
, the answer was correct this time!
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[10]; //smaller, but correct!
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
cout << "*" << pr[i] << endl;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
5
1 2 3 4 5
1
3
6
10
15
It seems that the problem happend at here:
pr[i] = pr[i-1] + x;
I know that the initial value of the array was 0, but why a smaller space works well and the higher space didn't ? The most interesting thing is that when I declare the array as a global variable, though small, the answer was correct?
#include <iostream>
using namespace std;
int pr[1]; //such a tiny space but correct!
int main()
{
int n; cin >> n;
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
The results:
//the input
5
1 2 3 4 5
//the output
1
3
6
10
15
This problem confuses me a whole day, can someone help me? I can't fell asleep as the problem was still there :(