The problem is a
is not a global variable.
What this means: for every depth of your recursion, a new variable a
is being created, ignored, then set to 1
and returned. As a
is a local variable, int a
is separate across depths of your recursion.
There are two ways you can go about fixing this.
- Make
a
a global variable. Your code could look something like this:
#include <stdio.h>
int string_length(char *s, int x);
int a = 0;
int main(void)
{
int length = 0, x;
char string[] = "This is a string";
x = string_length(string, length);
printf("The length of the string will be: %d\n", x);
return (0);
}
int string_length(char *c, int x)
{
if (*c != '\0')
{
a = a + 1;
string_length(c + 1, x + 1);
}
return (a);
}
Notice, all I did was move int a = 0
above int main(void)
. As a
is now a global variable, its value is preserved between different calls of your recursive function, meaning they are all doing a = a + 1
on the same global variable a
.
- Utilize
x
.
I've noticed that in your function, you keep track of int x
, yet never use it. int x
is tracking the depth of your recursion, and you can use this to return the string length.
Your code could look something like this:
#include <stdio.h>
int string_length(char *s, int x);
int main(void)
{
int length = 0, x;
char string[] = "This is a string";
x = string_length(string, length);
printf("The length of the string will be: %d\n", x);
return (0);
}
int string_length(char *c, int x)
{
if (*c != '\0')
{
return string_length(c + 1, x + 1);
} else
{
return x;
}
}
Notice, method 2 (the method shown directly above) is mostly always preferred. This is because declaring lots of variables globally can pollute the global namespace, which is not recommended an leads to unnecessarily messy code.