Reputation: 71
I'm trying to use the strstr function in C for a bigger project, and couldn't get it to work, so I formed a small test file to try and learn it better, only problem are results are not what I expected. Can someone please explain to me based on this c file I have, what strstr should return for me, and how I am using it wrong? When i run this program it is returning NULL for all uses of strstr, what I expect is that it returns NULL for the first 2, but for one of the second two (I know not both) it should print the string "brush". What am I doing wrong or expecting wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char str1[11]="toothpaste";
char str2[11]="toothbrush";
char str3[6]="brush";
char str4[6]="paste";
printf("\n\nstr1=%s",str1);
printf("\nstr2=%s",str2);
printf("\nstr3=%s",str3);
printf("\nstr4=%s",str4);
printf("\n\nResult of strstr(1,2) is %s",strstr(str1,str2));
printf("\nResult of strstr(2,1) is %s",strstr(str2,str1));
printf("\nResults of strstr(2,3) is %s",strstr(str1,str3));
printf("\nResults of strstr(3,2) is %s\n\n",strstr(str3,str1));
return 0;
}
Upvotes: 2
Views: 576
Reputation: 500923
The last two cases call strstr
on str1
and str3
(not str2
). Thus they're looking for "brush"
in "toothpaste"
and vice versa.
Upvotes: 4