0

I wrote this piece of code to find the GCD of any two numbers, and as I am working with multiple test cases, I used a 2D array with each testcase as a row and the first two elements in each row to store the numbers. FOr example, a[0][0] stores the first number of the first test case.

It works well up to user input, but the part which calculates the gcd, I'm getting a runtime error. I checked to see if I was trying to access an undefined location in the array, but with no luck.

const int testCase;
scanf("%d", &testCase);
int a[testCase][3], i, j, k;

for(k = 0; k < testCase; k++){
    scanf("%d %d", &a[k][0], &a[k][1]);
}

// problem occurs after this

for(j = 0; j < testCase; j++){
    
    for(i = 0; i <= a[j][0] && i <= a[j][1]; i++){
        if(a[j][0] % i == 0 && a[j][1] % i == 0){
            a[j][2] = i;
        }
    }
    printf("%d\n", a[j][2]);
Troy Bean
  • 11
  • 3
  • Why do you need to store results of each test case in a 2D array? Also, is this complete code? – kiner_shah Jan 02 '22 at 07:12
  • It seems that you miss an `else` case: `else a[j][2] = 0;`, otherwise you read uninitialized memory on `printf("%d\n", a[j][2]);` – David Ranieri Jan 02 '22 at 07:13
  • The code is dividing by 0 when `i` starts at 0. Try `for (i = 1, ...` – user3386109 Jan 02 '22 at 07:17
  • It *would* be initialized if the code ever got past `i = 0`. To make it more obvious that it's initialized, I'd add `a[j][2] = 1` *before* the `i` loop, and then start `i` at 2. – user3386109 Jan 02 '22 at 07:26

0 Answers0