Reputation: 33
I am trying to solve a problem from the CodeForces. The problem name is Sereja and Dima. I have a written code that keeps giving me 2 errors. 1st one is using uninitialized memory ans. 2nd is using uninitialized memory ans[ BYTE:0]. I am using Microsoft Visual Studio 2019. Any kind of help or suggestions would be appreciated. I am sharing my code here.
// Code by Neel Mehta
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n; cin >> n;
int ans[2];
int num[1000];
for (int i = 0; i < n; i++) {
cin >> num[i];
}
int l = 0;
int r = n - 1;
int f = 1;
while (l <= r) {
ans[f] += max(num[l], num[r]);
if (num[l] > num[r]) {
l++;
}
else {
r++;
}
f ^= 1;// 0001
// 0001
// 0000
}
cout << ans[1] << " " << ans[0];
return 0;
}
Upvotes: 3
Views: 158
Reputation: 2420
The compiler already told you what to do. What value are you supposing to be in ans If you haven't intialized It? Do you expect It to be 0? Then initialize: int ans[2] = {0};
or use vector that already initializes to 0 by default: vector<int> ans(2);
Remember that x += y;
is equivalent to x = x + y;
and, If that the first place that x
is being assigned to, then the result is unpredictable! (Unless x
happen to be global or static, which then would imply in an initialization to 0).
Upvotes: 3