I am trying to find out the factorial of a number using recursion and passing the pointers as function arguments. But this error appears all the time. Debugers and Coders! I need your assistance with this.
The code
#include<stdio.h>
int *factorial(int *);
int value, p=0, q=1, x, tmp;
void main() {
int *result;
puts("Enter the value::");
scanf("%d",&value);
result = factorial(&value);
printf("\nThe Result is::%d\n", *result);
}
int *factorial(int *n) {
if(*n == p || *n == q) {
return(&q);
}
else {
tmp = *n -1;
*n *= (factorial(&tmp));
return(n);
}
}
The error:
error: invalid operands to binary * (have ‘int’ and ‘int *’)
*n *= (factorial(&tmp));
This line :
*n *= (factorial(&tmp));
should be
*n *= *(factorial(&tmp));
however, be careful with this implementation because it is recursive, but uses pointers to globals.
Would the standard implementation not work for you?
int factorial(int n)
{
if(n==0)
return 1;
else
return factorial(n-1)*n;
}
With the standard, you need to prompt your user for non-negative values only.