我无法理解以下代码。尽管我尝试调试它一段时间,但似乎我无法理解代码的确切机制,并且感觉陷入困境。任何帮助将不胜感激。
编辑:嗯,我的问题主要在于递归函数以及它如何知道何时停止调用它自己。
int main(){
char word[10]="abcdfb";
doSomethingELSE(word);
printf("%s",word);
return 0;
}
void doSomethingELSE(char * w){
static char * s =NULL;
char t;
if(!s){
s=w;
}
if(*w==0)return;
doSomethingELSE(w+1);
if(s>w)return;
if(*w -*s==1){
t=*s;
*s=*w;
*w=t;
}
s++;
return;
}
最佳答案
递归函数调用在 doSomethingELSE(w+1)
获取“bcdfb”、“cdfb”、“dfb”、“fb”、“b”、“”之后停止 -> if(w[0] == '\0') 返回
。这将为每个 char
放置一个函数调用的执行堆栈,向后移动。 static
变量s
向前移动。清理之后,会发生什么就更清楚了:
#include <stdio.h> /* printf */
#include <string.h> /* strlen */
/* prototype */
void swapConsectutiveLetters(char * word);
/** Provides a word. */
int main(void) {
char word[10] = "abcdfb";
swapConsectutiveLetters(word);
printf("%s", word);
return 0;
}
/** Detects consecutive letters occurring in the n-th from first,
last and swaps them. */
void swapConsectutiveLetters(char * word) {
char * end;
/* Do nothing: null, empty, or 1-char string. */
if(!word || word[0] == '\0' || word[1] == '\0') return;
/* Obtain a pointer to the end of the string. */
end = word + strlen(word) - 1;
/* Swaps consecutive letters. */
do {
if(end[0] - word[0] == 1) {
char temp = word[0];
word[0] = end[0];
end[0] = temp;
}
} while(++word < --end);
}
关于c - 指针算术和 Char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46207516/