I was practicing some programming problems and tried to code the popular "reverse words in a string" problem. 

I tried to come up with my own code in C. I am able to partially get it right. That is, "hello world" becomes "world olleh". I am wondering what the bug is here. I think somewhere I am creating an off by 1 bug. 

As much as possible, I wanted to do it without using library functions. I searched here for this problem &amp; found many solutions, but I'd like to know why my solution doesn't work. 

Here is the code:

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

void reverse(char*, int);

int main(int argc, char **argv)
{
    char st[]= "hello world";
    int len = strlen(st);
    int i=0,j=0;

    reverse(st,len-1); // Reverse the entire string. hello world =&gt; dlrow olleh

    while(st[j]){ //Loop till end of the string
        if ( *(st+j) == ' ' || *(st+j) == '\0' ) { //if you hit a blank space or the end of the string
            reverse(st+i,j-1); // reverse the string starting at position i till position before the blank space i.e j-1
            i=++j; //new i &amp; j are 1 position to the right of old j
        }
        else {
            j++; //if a chacacter is found, move to next position
        }               
    }       

    printf("%s",st);
    return 0;
}

void reverse(char *s, int n)
{
    char *end = s+n; //end is a pointer to an address which is n addresses from the starting address
    char tmp;
    while (end&gt;s)  //perform swap
    {
        tmp = *end;
        *end = *s;
        *s = tmp;
        end--;
        s++;
    }
}


Thank you!

UPDATE: Based on @Daniel Fischer's answer, here is the correct implementation : http://ideone.com/TYw1k


Question: What are my chances of getting into the Tsukiji fish auction if I arrive by 5:25?
Answer: Aside from a few hungry all-night clubbers and the odd loaded sushi fanatic rolling up in a cab, everybody else will be in the same boat as you, so you're quite likely to get in if you arrive on the first train.

Also, while for some reason the auctions get all the press, the main event at Tsukiji is actually eating the world's best sushi.  I'm pretty sure you won't regret if you skip the auction entirely and go eat at Sushidai or Yamato Sushi instead.  Turning up early for these is a good idea as well, they're tiny and the queue to get in can be 1 hr plus if you get there late.