p1 is a pointer. It's value is the address of 'd', not 'd' itself. Same with s. It is a pointer and it's value is the address of 'a' in the string "abcd". Subtracting s from p1 gives the "distance" between the pointers, which is the answer.
About f("abcd", "bcd"), the answer is 0 since the very first letter of s is not in t, so the scan stops at that point.
Code:
#include <stdio.h>
int f(const char *s, const char *t) {
const char *p = s;
for (const char *q; *p; ++p) {
for (q = t; *q && *p != *q; ++q) ;
if (!*q) break;
}
return p - s;
}
int main() {
struct {
const char *s, *t;
int n;
} tests[] = {
{"abcd", "babc", 3},
{"aaaa", "x", 0},
{"xxxxxxtxxx", "qx", 6},
{"xxxx", "x", 4},
{"abcd", "bcd", 0}
};
int size = sizeof tests / sizeof tests[0];
for (int i = 0; i < size; ++i) {
printf("[%s] [%s]\n", tests[i].s, tests[i].t);
int n = f(tests[i].s, tests[i].t);
printf("%d", n);
if (n != tests[i].n)
printf(" WRONG: should be %d", tests[i].n);
putchar('\n');
}
return 0;
}