递归函数返回字符串

时间:2015-10-13 20:48:18

标签: c

我没有想法了。我只习惯处理递归函数的整数, 所以程序输出应该是:

Please enter a number : 4 
a
ab
abc
abcd 
abc 
ab
a
到目前为止,这是我想出的唯一一件事:

#include <stdio.h>
char arr [] ;
char*arr function(int count){
   char ch='a';
  if(count==1||count==count) 
     return ch;
  return (ch +function(count--)); 
 }//end method

main (){
  function(4);
 }//end main

1 个答案:

答案 0 :(得分:0)

由于字符串是C中的字符数组/指针(带有“NUL char标记结束”约定),因此获得“字符串作为值”的预期递归行为的方法是将字符数组包装在结构。像这样:

struct MyString {
    char s[10];
};

现在你会做类似的事情:

struct MyString f(int count, int index)
{
    struct MyString result;
    rslt.s[0] = 'a' + index;
    rslt.s[1] = '\0';
    if (count == 1) {
        return result;
    }
    strcat(result.s, f(--count, ++index).s);
    return result;
}

int main()
{
    f(4, 0);
}

我没有尝试在这里解决您的编程问题,只是说明了如何在递归函数中将字符串作为值处理。它对函数参数的作用方式相同,而不仅仅是结果。