0
#include <stdio.h>
void gcdFinder(int num1, int num2, int *result);
int main()
{
    int n1, n2, result;
    printf("Enter 2 numbers: \n");
    scanf("%d %d", &n1, &n2);
    gcdFinder(n1, n2, &result);
    printf("rGcd2(): %d\n", result);
    return 0;
}
void gcdFinder(int num1, int num2, int *result)
{
    printf("Initial : %d %d \n",num1,num2);
    *result=num1;
    if(num2 ==0 ){
        return;
    }else{
        gcdFinder(num2,(num1%num2),&result);
    }
}

I am trying to find the GCD the 2 inputs and storing the result into the result variable. However my code does not seem to work as it only stores one time. enter image description here

As the output suggest my final value for num1 should be 1 however it is not stored and it remains as 4.

  • Your compiler should have been warning you about the type mismatch between the expected argument type `int *` and the actual argument type `int **` for the third argument to the recursive call to `gcdFinder()`. Heed your compiler. It is always correct. When it deigns to complain about your code, it means it has found a bug. Typically, if it isn't sure it's a bug, it'll say nothing (unless you ask it to give you extra warnings). Use the maximum warning level you can work with, and don't even run code that generates any warnings when it is compiled. – Jonathan Leffler Sep 27 '18 at 06:05
  • THis might be interesting as well: https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c – Jabberwocky Sep 27 '18 at 06:31

1 Answers1

3

In the function gcdFinder change

gcdFinder(num2,(num1%num2),&result);

to

gcdFinder(num2,(num1%num2), result);
                           ^
                       No & as result is already a pointer here

Notice:

In main it's correct to use &result because result in main is an int

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63