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.
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
sarray intotarray.sis a pointer to beginning of array, andstrstrreturns a pointer to found occurence ORnullptr. So your code got two possible bugs:nullptr - sdoes not have defined result. Some implementations have it as ifswas an incorrect pointer (negative value) and some outright return0.kis greter thanstrlen(s)- second call of strstr does have risk to run into uninitialized memory, intotor fail, no check was there.