Your program is working mainly working as expected but not when the substring is at the end of the main string because you are not checking for the end of the strings. The terminating null characters will match too so that
j
becomes greater than the length of the sub string.
There is also another error which should be shown during compilation or during run-time with debug builds: The variable
j
may be used without initialisation. This can be avoided by placing the code that sets the
flag
into the above
if
condition.
Finally you should restore
i
when a charcter match has been found. This avoids also an overrun when matching at the end of main (then
i
points to the terminating null character, is incremented at the end of the loop and the following null check of the loop condition might fail).
The updated code part:
if(main[i]==sub[0])
{
pos=i,j=0;
while(sub[j]==main[i] && main[i] != '\0')
{
i++;
j++;
}
if(j==strlen(sub))
flag=1;
else
flag=0;
i = pos;
}