The program passes a char type to the function in the recursive case, while you'd want this to be a pointer. Iterating over a string given only a single character is not possible, we need to know where we are in the string.
As pointed out by various comments, using static is missing the point of writing a recursive function as it effectively introduces a global variable.
In fact, using an index variable is not necessary at all. You may simply use the pointer as an argument and parameter. Dereference it to obtain the character is currently points to, and increment it to make it point to the next character.
Corrected code, with a couple of improvements:
#include <stdio.h>
// Declare the function before it is used.
// It doesn't return anything, so the return type should be "void".
void fun(char *p);
int main(void) // Correct main signature when not using command line arguments
{
char *arr = "rama"; // We are not modifying the string, so a pointer to a string literal will do
fun(arr);
putchar('\n'); // Print a newline at the end of the program
}
void fun(char *p)
{
if (*p == '\0') // Get the character the pointer currently points to
return; // No need for an else if we return here
fun(p + 1); // Pass the increment pointer
putchar(*p); // Print the dereferenced pointer. No need for printf if we're just printing a single char
}
Another option is to make the function tail-recursive
(Inspired by a comment by Eugene Sh.). This requires an additional index parameter, but let's you print the final newline in de base case.
#include <stdio.h>
#include <string.h>
void fun(char *p, size_t idx);
int main(void)
{
char *arr = "rama";
fun(arr, strlen(arr) - 1);
}
void fun(char *p, size_t idx)
{
// Happens in both the base case and recursive case
putchar(p[idx]);
// Base case
if (idx == 0U)
{
putchar('\n');
return;
}
// Recursive case
fun(p, idx - 1);
}
staticvariables in recursion is kind of "cheating". The task can be accomplished with pure recursionfun(p[i]);is bad.