c - 指针算术和 Char 数组

标签 c pointers pointer-arithmetic

我无法理解以下代码。尽管我尝试调试它一段时间,但似乎我无法理解代码的确切机制,并且感觉陷入困境。任何帮助将不胜感激。

编辑:嗯,我的问题主要在于递归函数以及它如何知道何时停止调用它自己。

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/

相关文章:

c - 构建解释器 : designing an AST

c - 图书馆包括哪些功能?

C++ 用两种不同的方式初始化指针会产生两个答案

c++ - 只有数组的一个元素被传递给函数。 C++

c - 在 C 中遍历多维数组中的列的最快方法

c - 将函数放入 avr 中跳过字符

c - 堆栈实现错误

c++ - 使用带有自定义释放器的 std::unique_ptr 来包装原始指针

c++ - 带空终止符的指针数组交互

C++ 入门第 5 版。 : using sort on a vector of pointers is it undefined?