-2

I'm trying to understand this kind of program in C, but I can't. Exactly, I can't figure out how *s is changed, and why the compiler shows 210012.

#include <stdio.h> #include <stdlib.h> #include <string.h> void WhatIamDoing(char *s) { char ch; if (*s) { ch = *s; s++; WhatIamDoing(s); putchar(ch); } } int main() { char s[20] = "012" ; WhatIamDoing(s) ; printf( "%s", s ) ; } 
25
  • 5
    Sorry. This is no "explain the code" or tutoring site. See How to Ask. Commented Jun 14, 2016 at 17:58
  • @Olaf Who says that? Commented Jun 14, 2016 at 17:58
  • Have you heard of recursion? Specifically about head recursion? Commented Jun 14, 2016 at 18:00
  • "compiler shows 210012" --> Does not your output include l and k? Recommend posting output exactly. Commented Jun 14, 2016 at 18:01
  • @chux I did this for debugging. Commented Jun 14, 2016 at 18:02

1 Answer 1

6

I think it is easy to think this way. In void function char *s is a pointer that pointed to a char variable or char array. In your case it pointed to the char array s[20]="012". In WhatIamDoing function s is pointed to '0' character and it's assign to char ch variable. Then s++ now 's' is pointed to character '1'. Again you are calling the function WhatIamDoing(s), it also happens the same (this is like a recursive function) and in the last WhatIamDoing(s), char ch is assign as '2'. After all the characters are done, functions running (finally when it comes to null character) if condition is false. In last function by command putchar you print '2' then '1' then '0'. It means after you run the WhatIamDoing function you print the char array in reverse order. In main function you again print the s string. So then you get the the "210021". hope you get the idea.

Sign up to request clarification or add additional context in comments.

2 Comments

So, when *s is pointing to Null, if condition is get false. But why prints the array in reverse mode?
This is explained in answer - putchar prints characters of string in reversed order

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.