Reputation: 7
#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).
Upvotes: 0
Views: 192
Reputation: 40145
void rec(char pin[]){
if (*pin=='\0')
return;
else {
rec(pin + 1);
printf("%c", *pin);
}
}
Upvotes: 0
Reputation: 360
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???
Upvotes: 1
Reputation: 5842
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, i.e., 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.
Upvotes: 1
Reputation: 6606
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]);
}
Upvotes: 3