I'm trying to build my strstr() function, it's look all fine
but when I execute the code it return nothing ;
This is my function :
#include <stdio.h>
char* ft_strstr(char *str, char *to_find) {
char *a;
char *b;
b = to_find;
if (!*b)
return (char*) str;
while (*str) {
if (*str != *b)
continue;
a = str;
while (1) {
if (!*b)
return (char*) str;
if (*a++ != *b++)
break;
}
str++;
b = to_find;
}
return (NULL);
}
int main() {
char string[] = "Hello from morroco";
char find[] = "from";
ft_strstr(string, find);
printf("%s", find);
return 0;
}
I don't know what. I have to try to fix it cause it looks all fine for me.
There is a bug in this if statement
the pointer
stris not increased in this case and as a result the loop will be infinite.instead of the while loop it is better to use a for loop as
or the while loop can look like
Also it seems you mean
instead of
Pay attention to that the function should be declared like
And using such castings like
makes sense if the parameter
strhas the typeconst char *as it should have.