Search code examples
crecursioncompiler-errorsfunction-pointersfunction-definition

I can't spot the mistake in c program - Can't find the error


This my code for finding sum of n number, I have already solved it in iteration and recursion method by tried to implement function pointer and cannot find what the error is.

#include <stdio.h>

int num; 

int input(int *a)
{
    scanf("%d", a);
    return 0;
}

int sumOfNNumber(int (*number)(int*))
{
    number(&num);   
    if (num == 0) return 0;
    else  return num + sumOfNNumber(num - 1);
}

int main()
{
    sum_it = 0;
    int (*ptr)(int*) = &input;
    
    int sum_rc = sumOfNNumber(ptr);
    
    printf("%d\n", sum_rc);

    return 0;
}

This is error displayed in the compiler, I used the online gdb compiler. I also tried VS Code and error persisted.

main.c: In function ‘sumOfNNumber’:
main.c:24:37: warning: passing argument 1 of ‘sumOfNNumber’ makes pointer from integer without a cast [-Wint-conversion]
     else  return num + sumOfNNumber(num - 1);
                                     ^~~
main.c:19:5: note: expected ‘int (*)(int *)’ but argument is of type ‘int’
 int sumOfNNumber(int (*number)(int*))
     ^~~~~~~~~~~~
main.c: In function ‘main’:
main.c:29:5: error: ‘sum_it’ undeclared (first use in this function)
     sum_it = 0;
     ^~~~~~
main.c:29:5: note: each undeclared identifier is reported only once for each function it appears in
main.c:34:25: error: ‘number’ undeclared (first use in this function)
     for(int i = 0; i <= number; i++)
                         ^~~~~~

I think I have made mistake in implementing the function pointer but checked it and it correct. Please help me to solve the by pointing out the error means and is. Thank you.


Solution

  • Well, to answer your primary question right away: The compiler tells it there quite clearly:

    main.c: In function ‘sumOfNNumber’:
    main.c:24:37: warning: passing argument 1 of ‘sumOfNNumber’ makes pointer from integer without a cast [-Wint-conversion]
         else  return num + sumOfNNumber(num - 1);
    

    You invoke sumOfNNumber which expects a function pointer. However, what you pass is the result of an integer operation:

    sumOfNNumber(num - 1);
    

    However there is more in your code that - in my eyes - has to be addressed:

    1. Using call by reference or using a global variable is not how your recursive algorithm is supposed to work. Especially given the fact, that you do not alter that value at all.
    2. I don't quite understand, why you intend to use function pointers for that assignment? In fact you have a weird mixture of static recursion and usage of the function pointer. So what do you want to achieve exactly?

    Maybe you want to reassess your approach in the light of those comments aswell.