Good morning everyone, I have to simulate the operation of the strstr()
function with a function written by me.
In the code I slide the original string in a temporary string and then the comparison with the string to look for, if they are equal it should return 1
.
But even if the strings are equal and of the same length the code never enters the if
cycle and therefore never returns 1
.
My code:
int *strstr_new(char *s7, char *s8) {
int length_s7 = strlen(s7);
int length_s8 = strlen(s8);
char search_string[length_s8];
printf("%d\n", length_s8);
for(int i=0; i<length_s7; i++) {
for(int j=0; j<length_s8; j++) {
search_string[j] = s7[i+j];
search_string[j+1] = '\0';
}
printf("%s\n", s8);
printf("%s\n", search_string);
printf("%d\n", length_s8);
printf("%d\n", strlen(search_string));
//search_string[length_s8+1] = '\0';
if(search_string == s8) {
return(1);
}
}
if(search_string != s8) {
return(NULL);
}}
Does someone have an idea of where I'm wrong?
Thanks!
The function declaration
looks very strange.
For example why is the return type
int *
? Why are function parameters nameds7
ands8
instead of for examples1
ands2
? Why are not the function parameters qualified withconst
?Creating a variable length array within the function is inefficient and redundant and can lead to stack exhaustion.
This loops
invokes undefined behavior because this statement
writes beyond the array when
j
is equal tolength_s8 - 1
.In this statement
there are compared two pointers and it is evident that they are unequal because they point to different arrays.
Without using standard C functions except the function
strlen
(that could be also defined explicitly) the function can be declared and defined the following wayThe program output is
If you are allowed to use standard string functions along with
strlen
then the loop within the functionstrstr_new
can be simplified the following way