0

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 :)

David G
  • 94,763
  • 41
  • 167
  • 253

1 Answers1

1
  • Your int product[1][cases]; is before cin >> cases;, so the input will not be used for allocation.
  • You declared int product[1][cases];, so only product[0] is allowed and using product[1] is out-of-range (invalid).
  • Variable-length array is not in C++ standard.

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70