char* func( char* a, const char* b )
{
while( *a )
{
char *s = a, *t = b;
while( (*s++ == *t++) && *s && *t );
if( *t == 0 )
return a;
a++;
}
return 0;
}
The above code was written to search for the first instance
of string “b” inside of string “a.”
Is there any problem with the above program?
Is there any approach to improve the efficiency of it?
If a points to “cat” and b points to “ab”, func will return a pointer to “at” (the wrong value) instead of 0 (the intended value) because the pointer t is incremented even though the comparison (*s++ == *t++) fails.
For completeness’ sake and in order to answer the second question, I’d offer one solution (surely among other viable ones): Have the result of the comparison be assigned to another variable, e.g.
while( ( flag = ( *s++ == *t++ ) ) && *s && *t );and thenif( flag && *t == 0 ).