Reputation: 3
I know its a invalid memory reference error, but I can't seem to find the cause of the error in my code.
I just tried my problem on Hackerearth, it was the 'Find Product' https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-product/ and my submission was this, which gave me no errors on codeblocks compiler, but pops a Runtime Error(SIGSEGV).
#include <iostream>
using namespace std;
int main() {
int cases;
int pro = 1;
int product[1][cases];
cin >> cases;
for (int x = 0; x < cases; x++) {
cin >> product[1][x];
}
for (int x = 0; x < cases; x++) {
pro *= product[1][x];
}
cout << pro;
}
Thanks in advance :)
Upvotes: 0
Views: 502
Reputation: 75062
int product[1][cases];
is before cin >> cases;
, so the input will not be used for allocation.int product[1][cases];
, so only product[0]
is allowed and using product[1]
is out-of-range (invalid).Try this:
#include <iostream>
using namespace std;
int main() {
int cases;
int pro = 1;
cin >> cases;
int* product = new int[cases];
for (int x = 0; x < cases; x++) {
cin >> product[x];
}
for (int x = 0; x < cases; x++) {
pro *= product[x];
}
cout << pro;
delete[] product;
}
Upvotes: 1