指针运算和字符数组
Pointer Arithmetics and Char array
我无法理解以下代码。尽管我尝试调试了一段时间,但似乎我无法理解代码的确切机制,而且我感到卡住了。任何帮助将不胜感激。
编辑:好吧,我的问题主要在于递归函数以及它如何知道何时停止调用它自己。
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] == '[=12=]') return
。这会为每个 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] == '[=10=]' || word[1] == '[=10=]') 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);
}
我无法理解以下代码。尽管我尝试调试了一段时间,但似乎我无法理解代码的确切机制,而且我感到卡住了。任何帮助将不胜感激。
编辑:好吧,我的问题主要在于递归函数以及它如何知道何时停止调用它自己。
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] == '[=12=]') return
。这会为每个 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] == '[=10=]' || word[1] == '[=10=]') 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);
}