Pointer Arithmetics and Char array

77 Views Asked by At

I am having trouble understanding the following code. Although I tried to debug it for some time it seems that I can't understand the exact mechanics of the code and I am feeling stuck. Any help will be deeply appreciated.

edit: Well my problem is mostly located on the recursive function and how it will know when to stop calling it self.

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;
}
1

There are 1 best solutions below

0
On BEST ANSWER

The recursive function calls stop after doSomethingELSE(w+1) gets "bcdfb", "cdfb", "dfb", "fb", "b", "" -> if(w[0] == '\0') return. This places an execution stack of function calls for each char, going backwards. The static variable s goes forward. After cleaning-up, it is more clear what happens:

#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);
}