Recode strstr in C
evolution
-
KX Posted messages 19031 Status Modérateur -
KX Posted messages 19031 Status Modérateur -
```c
char *my_strstr(char *str, char *to_find)
{
char *pointeur;
int i;
int j;
int counter;
pointeur = NULL;
i = 0;
j = 0;
counter = 0;
while (pointeur == NULL && str[i] != '\0')
{
if (str[i] == to_find[j])
{
while(str[i + j] == to_find[j])
{
j++;
if (to_find[j] == '\0')
{
return &str[i];
}
}
j = 0;
}
i++;
}
return pointeur;
}
```
char *my_strstr(char *str, char *to_find)
{
char *pointeur;
int i;
int j;
int counter;
pointeur = NULL;
i = 0;
j = 0;
counter = 0;
while (pointeur == NULL && str[i] != '\0')
{
if (str[i] == to_find[j])
{
while(str[i + j] == to_find[j])
{
j++;
if (to_find[j] == '\0')
{
return &str[i];
}
}
j = 0;
}
i++;
}
return pointeur;
}
```
2 réponses
It's your line *pointeur = to_find[i]; that crashes.
pointeur is NULL so *pointeur is not accessible.
Moreover, to_find[i] is a character, not a pointer.
If you want to offset the pointer to_find by 'i' positions, you can do to_find+i.
By changing your line to pointeur = to_find+i; it seems to work in my example my_strstr("bonjour","bon") but there might still be other bugs...
--
Trust does not exclude control.
pointeur is NULL so *pointeur is not accessible.
Moreover, to_find[i] is a character, not a pointer.
If you want to offset the pointer to_find by 'i' positions, you can do to_find+i.
By changing your line to pointeur = to_find+i; it seems to work in my example my_strstr("bonjour","bon") but there might still be other bugs...
--
Trust does not exclude control.