简体   繁体   中英

Reversed String Using Recursion Functions

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

void rec(char pin[]);

main()
{
      char pin[100];
      printf("Give word: ");
      scanf("%s", pin);
      rec(pin);
      system("pause");
}

void rec(char pin[])
{
     int i=0;
     if (pin[i]=='\0')
        return;

     else
     {    
        rec(pin[i+1]);
        printf("%c", pin[i]);

     }

}

Well seems not to work but I don't know why. (I am not allowed to use the for loop, the function strlen and things like that).

in rec function else part you are passing a element which should be address of element.so try this in else part

else
     {    
        rec(&pin[i+1]);
        printf("%c", pin[i]);

     }

Well, since your question is "why it doesn't work", might as well answer exactly that.

I'm going to assume that the re() declaration is just a typo for rec() -- of course you have to correct that.

In the first line of that function, you declare a variable, int i = 0; . However, that variable is never assigned to again. Scan the function for any assignment on i -- you won't find any. Therefore, that i variable is a constant 0. With that in mind, let's replace i by 0 and write the code again:

if (pin[0]=='\0')
    return;
else
{    
   rec(pin[1]);
   printf("%c", pin[0]);
}

The offending line is clearly rec(pin[1]) . The function expects a char * argument, ie, a string (note that char * and char [] are the same in function parameter declarations). However, pin[1] is just the second character of pin . What you're doing there is converting implicitly that character to a pointer and passing it to the function -- which is incorrect.

What you want to pass to rec() is the pointer to the second character, since that would make it a pointer to a string beginning at the second character of pin . So, the correct call would be rec(pin + 1) , not rec(pin[1]) . Since pin points to the first character of the string, pin + 1 points to the second.

This is not correct. First of all, you are using an automatic variable. so, 'i' will always be initialized to 0.

use static int i, and see carefully. you are throwing char to char*. so, you cannot throw rec(pin[i+1]); change this to rec(pin); and before printf("%c", pin[i]); decrement 'i', before calling rec recursively, increment 'i' . Last but not least, you are calling 'rec'. but function name is 're', where is c???

void rec(char pin[]){
    if (*pin=='\0')
        return;
    else {
        rec(pin + 1);
        printf("%c", *pin);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM