如何在递归函数中返回字符串数组或复制它?

时间:2014-12-11 23:57:13

标签: c arrays string recursion

我在add2_recur函数中遇到了问题。我想在字符串中添加一个字符数字。但我不知道如何将字符串返回到我的main函数,因此我可以打印出结果。我尝试使用函数指针,但我只返回字符串的第一个值。

有关如何执行此操作的任何建议都会有所帮助。

//check if string is valid

int digcheck_helper(char *theno, int start, int length) {

         int charToInt = *(theno+start);

         if(!((charToInt >= 48) &&(charToInt <= 57)))
             return 0;
         if(length == 0)
             return 1;

         return digcheck_helper(theno,start+1,length-1);
}

int digcheck(char *str, int start, int length) {

         return digcheck_helper(string,start,length);
}

/**********************
 ****add recursive function**/

void add2_recur(char *num1, char *num2, int start, int carryDig) {

         int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
         char *str = (char*) malloc(strlen(num1) + 2);

         sum = singleChar1 + singleChar - 96;

         if(carryDig == 1)
            sum = sum + 1;
         if(start < strlen(num1)) {

                if(sum >= 10) {

                    sum = sum - 10;
                    str[start] = sum + 48;
                    carryDig = 1;
                    printf("sum of single digit is: %c\n", str[start]);
                }
                else if( sum < 10) {

                    str[start] = sum + 48;
                    carryDig = 0;
                    printf("sum of single digit is: %c\n", str[start]);
               }

                    add2_recur(num1,num2,start+1,carryDig);
         }
         else if ((start == strlen(num1)) && (carryDig ==1)){ 
                    str[start+1] = 48;
                    printf("sum of single digit is: %c\n", str[start+1]);
         }
}

void add2(char *n1, char *n2) {

        add2_recur(n1,n2,0,0)

}


/*******************/

int main() {

         char string1[20000], string2[20000], revStr1[20000], revStr2[20000];
         int digit_1, digit_2, i;

         printf("Enter first number >");
         fgets(string1,20000,stdin);

         string1[strlen(string1)-1] = '\0';
         digit_1 = digcheck(string1,0,strlen(string1)-1);

         //Check if string is valid integer

         if(digit_1 = 0)
             printf("This number is invalid\n");
         else{

                printf("Enter second number >");
                fgets(string2,2000,stdin);

                string2[strlen(string2)-1] = '\0';
                digit_2 = digcheck(string2,0,strlen(string2-1);

                if(digit_2 == 0)
                     printf("This number is invalid\n");
                else
                     printf("1st num is %s\n2st num is %s\n", string1, string2);
         }


         // reverse string
          for(i=0;i<strlen(string1);i++)
               revStr1[i] = string1[(strlen(string1)-1) - i];

          for(i=0;i,strlen(string2);i++)
               revStr2[i] = string2[(strlen(string2) -1) - i];

         // compare string and pass to add2
          if(strlen(revStr1) < strlen(revStr2)) {

               for(i = strlen(revStr1); i < strlen(revStr2); i++)
                  revStr1[i] = '0';

               add2(revStr1,revStr2);
          }
          else if(strlen(revStr2) < strlen(revStr1)) {

                 for(i = strlen(revStr2); i < strlen(revStr1); i++)
                     revStr2[i] = '0';

                add2(revStr1,revStr2);
          }
          else 
                add2(revStr1,revStr2);


        return 0;
}

4 个答案:

答案 0 :(得分:0)

this function:

void add2(char *n1, char *n2) 
{
    add2_recur(n1,n2,0,0)
}

this function has a couple of problems.
1) it will not compile because the statement that calls add2-recur() 
   is missing a trailing ';'

2) this function is not needed as add2_recur can be called directly

3) this is expected to add two numbers together .. 
   How is it to return the result?  
   It (probably) should be more like:

void add2(char *n1, char *n2, char *sum) 
{
    strcpy(sum, add2_recur(n1,n2,0,0) );
}

答案 1 :(得分:0)

好吧,我通过创建指针函数来修复代码,并使用malloc将值存储到 str 数组中。我注释掉了代码。但它仍然只将数组的第一个元素从堆返回到main函数。我如何让它返回整个阵列?

//检查字符串是否有效

int digcheck_helper(char * theno,int start,int length){

     int charToInt = *(theno+start);

     if(!((charToInt >= 48) &&(charToInt <= 57)))
         return 0;
     if(length == 0)
         return 1;

     return digcheck_helper(theno,start+1,length-1);

}

int digcheck(char * str,int start,int length){

     return digcheck_helper(string,start,length);

}

/ **********************  ****添加递归函数** /

char * add2_recur(char * num1,char * num2,int start,int carryDig){

     int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
     char *str = (char*) malloc(strlen(num1) + 2), sum;

     sum = singleChar1 + singleChar - 96;

     if(carryDig == 1)
        sum = sum + 1;
     if(start < strlen(num1)) {

            if(sum >= 10) {

                sum = sum - 10;
                str[start] = sum + 48; //store value in each element of an array
                carryDig = 1;
                printf("sum of single digit is: %c\n", str[start]);
            }
            else if( sum < 10) {

                str[start] = sum + 48; //store value in each element of an array
                carryDig = 0;
                printf("sum of single digit is: %c\n", str[start]);
           }

                add2_recur(num1,num2,start+1,carryDig);
     }
     else if ((start == strlen(num1)) && (carryDig ==1)){ 
                str[start+1] = 49; // store value in each element of an array
                printf("sum of single digit is: %c\n", str[start+1]);
     }

      return str;

}

/ ******************* /

int main(){

     char string1[20000], string2[20000], revStr1[20000], revStr2[20000], *addResult;
     int digit_1, digit_2, i;

     printf("Enter first number >");
     fgets(string1,20000,stdin);

     string1[strlen(string1)-1] = '\0';
     digit_1 = digcheck(string1,0,strlen(string1)-1);

     //Check if string is valid integer

     if(digit_1 = 0)
         printf("This number is invalid\n");
     else{

            printf("Enter second number >");
            fgets(string2,2000,stdin);

            string2[strlen(string2)-1] = '\0';
            digit_2 = digcheck(string2,0,strlen(string2-1);

            if(digit_2 == 0)
                 printf("This number is invalid\n");
            else
                 printf("1st num is %s\n2st num is %s\n", string1, string2);
     }


     // reverse string
      for(i=0;i<strlen(string1);i++)
           revStr1[i] = string1[(strlen(string1)-1) - i];

      for(i=0;i,strlen(string2);i++)
           revStr2[i] = string2[(strlen(string2) -1) - i];

     // compare string and pass to add2
      if(strlen(revStr1) < strlen(revStr2)) {

           for(i = strlen(revStr1); i < strlen(revStr2); i++)
              revStr1[i] = '0';

           add2(revStr1,revStr2);
      }
      else if(strlen(revStr2) < strlen(revStr1)) {

             for(i = strlen(revStr2); i < strlen(revStr1); i++)
                 revStr2[i] = '0';

           addResult = add2(revStr1,revStr2);
      }
      else 
            addResult = add2(revStr1,revStr2);


     // print out
     printf("sum is: %s\n", addResult);

    return 0;

答案 2 :(得分:0)

在C中,通常不通过return实际字符串来实现这样的事情。相反,您可以使用指向传递给您的缓冲区的指针。请使用实际返回值来报告状态消息。

为了不破坏你的实际任务,让我们定义一个简单的递归函数,它将返回一个字符串,其中包含所有非字母数字字符:

#include <stdio.h>
#include <string.h>

int strip_stuff_rec(const char *input, char *output, unsigned int offset_input, unsigned offset_output) {
    // Retrieve the character and move the offset
    const char c = input[offset_input++];

    if (c == '\0') { // Terminator; we're done!
        // Terminate the output string
        output[offset_output] = '\0';
        return 1; // Signal success
    }

    // Character is alphanumeric?
    if (isalnum(c)) {
        // Append the character to our result and move the offset
        output[offset_output++] = c;
    }

    // To have an error case, let's just pretend the string must not include @!
    if (c == '@') {
        return 0; // Signal an error
    }

    // Now handle the next position
    return strip_stuff_rec(input, output, offset_input, offset_output);
}

int strip_stuff(const char *input, char *output) {
    // Reset the output
    output[0] = '\0';
    // Start the recursive calls
    return strip_stuff_rec(input, output, 0, 0);
}

int main(int argc, char **argv) {
    // First let's set some input string
    const char *input = "Hello World! -- I've had a wonderful day!";
    // And we'll need a buffer for our result
    char result[256];

    // Now call the function and check the return value to determine
    // whether it's been successful.
    if (strip_stuff(input, result) == 0) {
        printf("Some error happened!\n");
    }
    else {
        printf("The stripped string is '%s'.\n", result);
    }
}

答案 3 :(得分:0)

由于传递整个数组不是很理想,因此C通常在大多数表达式中将其转换为指针。

传递整个数组的一种方法是将其包含在结构中。 (虽然不是一个好的解决方案)

typedef struct
{
   char s[128];
}MYSTR;