title: Finding the last occurrence of a string in a sentence in C
body: <p>I am practicing and I came across an exercise. The exercise says I am to manually write a function that finds the index of the last occurrence in a string. Now, I get that this has maybe been asked before but I cannot find what is the problem with my code. It works for almost all instances, but not so when <em>the last occurrence of the word is at the beginning of the string</em>.</p>
  
  <p>What I have tried: I used pointers to store the addresses of the <em>ends</em> of both the sentence and the word we are looking for. I then used a while loop to iterate through the string. If the current character matches the <em>last</em> character of the word we are searching for, we enter another while loop which compares the two. If the pointer that points to the beginning of the word and the one we used to iterate through the word are equal, the word is found. </p>
  
  <p>Here is some code: </p>
  
  <pre><code>
  #include &lt;stdio.h&gt;
  
  int find_last( char *str,  char *word)
  {
      char *p, *q;
  
      char *s, *t;
  
      p=str;                            /* Pointer p now points to the last character of the sentence*/
      while(*p!='\0') p++;
      p--;
  
      q = word;
      while(*q!='\0') q++;             /* Pointer q now points to the last character of the word*/
      q--;
  
      while(p != str) {
          if(*p == *q) {
              s=p;                        /* if a matching character is found, "s" and "t" are used to iterate through */
              /* the string and the word, respectively*/
              t=q;
  
              while(*s == *t) {
                  s--;
                  t--;
              }
  
              if(t == word-1) return s-str+1;  /* if pointer "t" is equal by address to pointer word-1, we have found our match. return s-str+1. */
          }
          p--;
      }
      return -1;
  }
  
  int main()
  {
      char arr[] = "Today is a great day!";
  
      printf("%d", find_last(arr, "Today"));
  
      return 0;
  }
  </code></pre>
  
  <p>So, this code should return <code>0</code> but it returns <code>-1</code>.</p>
  
  <p>It works in every other instance I tested! When ran in CodeBlocks, the output is as expected (<code>0</code>), but using any other online IDE I could find the output is still -1.</p>