Sta*_*los -2 c recursion pointers function
我试图用 C 语言理解这种程序,但我不能。确切地说,我无法弄清楚 *s 是如何更改的,以及为什么编译器显示 210012。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void WhatIamDoing(char *s) {
char ch;
if (*s) {
ch = *s;
s++;
WhatIamDoing(s);
putchar(ch);
}
}
int main() {
char s[20] = "012" ;
WhatIamDoing(s) ;
printf( "%s", s ) ;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为这样想很容易。在 void 函数中char *s是一个指向char变量或字符数组的指针。在您的情况下,它指向 char 数组s[20]="012"。在WhatIamDoing函数s中指向'0'字符并分配给char ch变量。然后s++现在 's' 指向 character '1'。再次调用函数WhatIamDoing(s),它也会发生同样的情况(这就像一个递归函数),并且在最后WhatIamDoing(s),char ch被赋值为'2'。完成所有角色后,
(最后当涉及到空字符时)如果条件为假。在最后一个函数中,putchar你打印'2'then '1'then '0'。这意味着在运行该WhatIamDoing函数后,您以相反的顺序打印字符数组。在 main 函数中,您再次打印 s 字符串。那么你就得到了"210021". 希望你明白。