c - Pointer Arithmetics and Char array -
i having trouble understanding following code. although tried debug time seems can't understand exact mechanics of code , feeling stuck. appreciated.
edit: problem located on recursive function , how know when stop calling 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; }
the recursive function calls stop after dosomethingelse(w+1)
gets "bcdfb", "cdfb", "dfb", "fb", "b", "" -> if(w[0] == '\0') return
. places execution stack of function calls each char
, going backwards. static
variable s
goes forward. after cleaning-up, more clear happens:
#include <stdio.h> /* printf */ #include <string.h> /* strlen */ /* prototype */ void swapconsectutiveletters(char * word); /** provides word. */ int main(void) { char word[10] = "abcdfb"; swapconsectutiveletters(word); printf("%s", word); return 0; } /** detects consecutive letters occurring in n-th first, last , swaps them. */ void swapconsectutiveletters(char * word) { char * end; /* nothing: null, empty, or 1-char string. */ if(!word || word[0] == '\0' || word[1] == '\0') return; /* obtain pointer end of string. */ end = word + strlen(word) - 1; /* swaps consecutive letters. */ { if(end[0] - word[0] == 1) { char temp = word[0]; word[0] = end[0]; end[0] = temp; } } while(++word < --end); }
Comments
Post a Comment