c++pointersabstract-data-type

I don't surely understand why this code works. Especially at the part "i=strstr(s + k, t) - s;", from my understanding the strstr() returns a pointer


The program does what is supposed to do, to extract the last occurence of a string in a string, but since strstr() is returning a pointer, why does the "minus string" do to make it unsigned and give the value of the last occurence?

Input:

ana si mariana canta la nai
na

Ouput:

ana si mariana canta la i

The code is bellow:

#include <iostream>
#include <cstring>

using namespace std;

char s[256], t[256];
int main()
{
    unsigned i, n, k = 0, x = 0;
    gets(s);
    gets(t);
    n = strlen(t);
    while(k < strlen(s) && x < strlen(s))
    {
        i = strstr(s + k, t) - s;
        k = i + n;
        x = strstr(s + k, t) - s;
    }
    strcpy(s + i, s + i + n);
    cout << s;
    return 0;
}

I tried to change data types from pointer to unsigned or int, see what happens, change the position of "s", like "s - strstr(...)" but the code didn't work anymore.


Solution

  • If two pointers refer to elements of same array (or one element beyond the end), result of substraction is a signed distance netween them, in elements, where result is positive if left pointer refers to an element with greater index.

    Aside from output this is ideomatically a C code, not C++ code. It contains typical mistakes one can use with pointer arithmetics and contains possible buffer overrun - you are slipping from s array into t array.

    s is a pointer to beginning of array, and strstr returns a pointer to found occurence OR nullptr. So your code got two possible bugs: