It should return 4 using gets() [unless gets() retrieved the newline from the input, in which case it would return 5], but it would be wrong anyway. What is happening is "i" moves through BOTH strings, when you really want it to just move through the "str".
So the idea is to start b back at sub[0] every run. But be sure to check "a" for null while looping, because *a == *b will be true when they both reach their null terminators, and the pointers will just happily fly through unowned memory...
Code:
int search(char *str,char *sub) {
int len=strlen(str),i;
char *a,*b;
for(i=0;i<len;i++) {
a=&str[ i ];
b=&sub[ 0 ];
while(*a && *a==*b) {
a++;
b++;
}
if(!*b) return i+1;
}
return 0;
}
Still, I would complain that first of all, strlen is just double work, it just loops through a string till it reaches a null anyway, so you can discard it completely. Finally, since pointers calculate indexes just as well as a counter, you can replace "i" too.
Code:
int search(char *str,char *sub)
{
char *a, *b, *c;
for(a = str; *a; a++)
{
c = a;
b = sub;
while(*a && *a==*b)
{
a++;
b++;
}
if(!*b)
return (int)(c - str)+1;
}
return 0;
}