I'm trying to implement a strlen
function in C with recursion and for some reason it's returning a 4 times bigger value than expected.
int *strlen(char *s)
{
if(*s == '\0')
return 0;
else
return 1 strlen(s 1);
}
Interestingly, when I change the type return of the function to "char", I get the desired result. I don't understand why, it should return an int anyways. I copied this code from a book, it should be right.
CodePudding user response:
Your function returns a pointer. On your system, an int
is 4 bytes. Pointer arithmetic means that adding 1 to an int pointer increases its value by 4. When you change the return value to char *
it "works" because char
is 1 byte, so pointer arithmetic means that adding 1 to a char pointer increments its value by 1.
Your function does not need to return a pointer at all.
int strlen(char *s)
{
if (*s == '\0')
return 0;
else
return 1 strlen(s 1);
}
It'd be even more appropriate to have it return size_t
than int
.
CodePudding user response:
strlen
should returnsize_t
notint
.- You return a pointer instead of an integer.
size_t mystrlen(const char *str)
{
return *str ? 1 mystrlen(str 1) : 0;
}
int main(int argc, const char *argv[])
{
printf("%zu\n", mystrlen("Hello"));
}
I copied this code from a book, it should be right
If they want you to return pointer to the integer then maybe they want something weird like this:
int *mystrlen(const char *str)
{
static int first = 1;
static int size = 0;
if(first) {size = 0; first = 0;}
if(*str)
{
size ;
mystrlen(str 1);
}
else
{
first = 1;
}
return &size;
}
int main(int argc, const char *argv[])
{
printf("%d\n", *mystrlen("Hello"));
printf("%d\n", *mystrlen(" World"));
}