0
char r[255], word[255], * ind;
    int n = 0;
    gets_s(r);
    gets_s(word);
    ind = r - 1;
    while (ind = strstr(ind+1 , word))n++;

    printf("%d\n", n);

This is a code that my friend sent me for an assignment. We have to find how many times a given word (word in code) appears in a sentence (r in code). Now I don't understand this part ind=r-1. What happens when we subtract a number from a string?? After playing around and testing the code it seems that this needs to be implemented so that if a word that we check for is the first word in the sentence it will also check it and include it into the final tally n. So the question is what happens when we subtract a number like 1 from a string. Thanks in advance!!!!

  • 3
    It's [pointer arithmetic](https://stackoverflow.com/questions/394767/pointer-arithmetic) -- you're not subtracting from the string, but from the pointer to the first element of the string. The subtraction is used so that the first `strstr` call will start searching from the correct location. – He3lixxx Jun 13 '21 at 19:34
  • Note that you can use arrays everywhere where a pointer is valid – in such cases, the array *decays* to a pointer to its first element automatically. – Aconcagua Jun 13 '21 at 19:42

0 Answers0