[英]backwards recursive printing in C
I'm trying out recursion and tried this exercise to print a word backwords. 我正在尝试递归,并尝试了此练习以打印单词backword。 What am i doing wrong?
我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
void recursivePrint(char* x){
if (*x = '\0')
return;
else
recursivePrint(x++);
printf("%c", *x);
}
int main()
{
char x[10] = "Hello";
recursivePrint(x);
return 0;
}
=
is an assignment operator. =
是赋值运算符。 And ==
is used for comparison. 和
==
用于比较。 Change 更改
if (*x = '\0')
To 至
if (*x == '\0')
EDIT: 编辑:
To see the first character, 要看到第一个字符,
Change 更改
void recursivePrint(char* x){
if (*x == '\0')
return;
else
recursivePrint(x++);
printf("%c", *x);
}
To 至
void recursivePrint(char* x){
if (*x == '\0')
return;
else
recursivePrint(x+1);
printf("%c", *x);
}
Aside from the assignment that was meant to be a comparison (as pointed out in another answer), you shouldn't increment x
, since you will want to output it after the recursive call. 除了要进行比较的赋值(如另一个答案中指出的那样)之外,您不应该递增
x
,因为您希望在递归调用之后将其输出。 Incrementing x
is unnecessary and as you can see is error-prone. x
增量是不必要的,如您所见,它容易出错。 What is happening is that the call number i
is printing character i+1
, so the second to last call is actually passing the null terminator to printf()
; 发生的情况是,呼叫号码
i
正在打印字符i+1
,因此倒数第二次呼叫实际上是将空终止符传递给printf()
; the third to last is passing the character before the NULL, etc. See it like this: 第三个倒数是在NULL之前传递字符,等等。如下所示:
recursivePrint("Hello");
recursivePrint("ello");
recursivePrint("llo");
recursivePrint("lo");
recursivePrint("o");
recursivePrint("");
return;
/* x was incremented, points to \0 */
print '\0'
/* x was incremented, points to "o" */
/* ... */
So basically, you are always one character ahead of the one you want to print. 因此,基本上,您总是比要打印的字符领先一个字符。 You can fix it by passing
x[-1]
to printf()
, but that is ugly. 您可以通过将
x[-1]
传递给printf()
来修复它,但这很丑陋。 A better approach would be: 更好的方法是:
void recursivePrint(char *x) {
if (*x == '\0')
return;
recursivePrint(x+1);
printf("%c", *x);
}
This is better because you never wanted / needed to increment x
in the first place. 这样比较好,因为您根本不需要/不需要先增加
x
。
Try this 尝试这个
void recursivePrint(char* x){
if (*x == '\0')
return;
recursivePrint(x+1);
printf("%c", *x);
}
You're close, but some of the answers here are incorrect and generate segfaults. 您接近了,但是这里的一些答案不正确,并会产生段错误。
#include <stdio.h>
#include <stdlib.h>
void recursivePrint(const char *x) {
if (*x == '\0') {
return;
}
recursivePrint(x+1);
printf("%c", *x);
}
int main(void) {
const char* x = "Hello";
recursivePrint(x);
return 0;
}
You should really use const char*
since your function doesn't modify the data. 您应该真正使用
const char*
因为您的函数不会修改数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.