在c中使用递归的strlen函数 [英] strlen function using recursion in c

查看:59
本文介绍了在c中使用递归的strlen函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是递归主题的新手,我一直在尝试使用递归编写strlen"函数,这就是我尝试过的:

I'm kida new to the recursion subject and i've been trying to write the "strlen" function using recurion, thats what i tried:

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;
}

在我的主函数中

int main()
{
     char word[MAX_DIGITS];
     scanf("%s",word);
     printf("%d", strlen(word,0));
     return 0;
}

但是我的程序每次运行都会崩溃,我错过了什么?(顺便说一句,我正在使用 C90)

but my program would crash whenever i run it, what am I missing? (I'm using C90 btw)

推荐答案

你的问题从这里开始:

i++

这称为后缀.只需使用 ++ii + 1

This is called a postfix. Just use ++i or i + 1

Postfix 发送值,然后增加变量.就像这样写:

Postfix sends the value and just then increments the variable. It's like writing this:

return strlen(str,i);
i = i + 1;

您必须使用 Prefix,它会增加变量然后发送值.前缀 (++i) 的作用如下:

You have to use Prefix, which increments the variable and then sends the value. A prefix (++i) will act like that:

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.

这篇关于在c中使用递归的strlen函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆