[英]strlen function using recursion in c
I'm kida new to the recursion subject and i've been trying to write the "strlen" function using recurion, thats what i tried: 我是新来的递归主题,我一直在尝试使用递归编写“ strlen”函数,这就是我尝试过的东西:
int strlen ( char str[], int i)
{
if ( str[i] == 0) return i+1;
return strlen(str,i++);
}
and i tried something very similiar 我尝试了类似的东西
int strlen( char str[], int i)
{
if ( str[i] == 0) return 1;
return strlen(str,i++) + 1;
}
and in my main function 而在我的主要职能
int main()
{
char word[MAX_DIGITS];
scanf("%s",word);
printf("%d", strlen(word,0));
return 0;
}
but my program would crash whenever i run it, what am I missing? 但是我的程序每次运行都会崩溃,我缺少什么? (I'm using C90 btw)
(我正在使用C90 btw)
Your problem starts here: 您的问题从这里开始:
i++
This is called a postfix. 这称为后缀。 Just use
++i
or i + 1
只需使用
++i
或i + 1
Postfix sends the value and just then increments the variable. Postfix发送值,然后增加变量。 It's like writing this:
就像这样写:
return strlen(str,i);
i = i + 1;
You have to use Prefix, which increments the variable and then sends the value. 您必须使用前缀,该前缀会使变量递增,然后发送值。 A prefix (
++i
) will act like that: 前缀(
++i
)的作用如下:
i = i + 1;
return strlen(str,i);
Or just send the value without changing the variable: 或者只发送值而不更改变量:
return strlen(str, i + 1);
Which, in my opinion, is the simplest way to do that. 我认为这是最简单的方法。
size_t strlen (char* str) {
if (*str == 0) {
return 0;
}
return strlen (str+1) +1;
}
So : 因此:
strlen ("") == 0
strlen ("a") -> strln("") + 1 == 1
strlen ("he") -> strln("e") + 1) = (strln("") + 1) + 1 == 2
etc 等等
return strlen(str,i++);
You are using the wrong increment operator. 您使用了错误的增量运算符。
i++
means the original value of i
is passed as argument, and then it's incremented. i++
装置的初始值i
作为参数传递,然后它的递增。 That means infinite recursion. 这意味着无限递归。
You should try ++i
instead, or better, i + 1
. 您应该改用
++i
或更佳的i + 1
。
If you want to keep the same prototype as strlen
does. 如果要保留与
strlen
相同的原型。 This is how i see a strlen with recursion. 这就是我看到递归的惊奇之处。
size_t strlen(char *str)
{
static int i = 0;
if (*str != '\0')
{
i++;
return ft_strlen(++str);
}
return i;
}
I know it's not the best way to do it. 我知道这不是最好的方法。 Just my implementation.
只是我的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.