The code below is a function that functions to search for a string in a string. I have a question because I don't understand something while analyzing the code.
The first of the two codes below works fine, but the second one does not.
1.<Normal operation code>
#include <stdio.h>
char* my_strstr(char* str1, char* str2);
int main() {
char str1[] = "iamaboyansdyour a girl";
char str2[] = "boy";
printf("%s\n", my_str(str1, str2) ? "head string contains each other" : "head string does not contain each other");
return 0;
}
char* my_strstr(char* str1, char* str2) {
char* s, * p;
for (; *str1; str1++) {
for (s = str1, p = str2; *s && *p && *s == *p; s++, p++) { ; }
if (*p == 0) { return (char*)str1; }
}
return NULL;
}
#include <stdio.h>
char* my_strstr(char* str1, char* str2);
int main() {
char str1[] = "iamaboyansdyour a girl";
char str2[] = "boy";
printf("%s\n", my_str(str1, str2) ? "head string contains each other" : "head string does not contain each other");
return 0;
}
char* my_strstr(char* str1, char* str2) {
char* s, * p;
for (; *str1; str1++) {
for (s = str1, p = str2; *s && *p && *s == *p; s++, p++) {
if (*p == 0) { return (char*)str1; }
}
}
return NULL;
}
What I'm curious about is the block of the second gun in the user-defined function.
for (s = str1, p = str2; *s && *p && *s == *p; s++, p++) { ; }
if (*p == 0) { return (char*)str1; }
for (; *str1; str1++) {
for (s = str1, p = str2; *s && *p && *s == *p; s++, p++) {
if (*p == 0) { return (char*)str1; }
}
The above two codes have different values when the range of the block is different in the second gun, but I don't know the difference between the two codes. The reason is that both codes return the address value (str1) at that time because *p meets you, and when it actually works, only the first code *p meets you and returns str1.
To explain more about what I understand, the first code is to evaluate the second gun after the first gun is evaluated, and then the second code is to evaluate the IF moon after the first gun is evaluated, and the second code is to evaluate the return when the second gun meets you, so I wonder why the second gun will eventually meet you
I'm so sleepy that my words are weird I think I'll have to sleep a little longer and study it again If my understanding is wrong, I would appreciate it if you could give me a feedback
c string function
The if condition must be *p>=0.
© 2024 OneMinuteCode. All rights reserved.