I am trying to search for a string in a string pointer. I am not sure how to explain exactly what I am trying to achieve, but I will try my best.
Let's say I have two string pointers char *p = "hello world" and char *q = "world", as world is in hello world, so I want to return a pointer *start that points to the w of *p. I hope that makes sense, if not then feel free to comment below.
Note: Unfortunately, I am not allowed to use any string.h library functions except strlen(), and also I am not allowed to use indexing in fact I am not allowed to use any square brackets [].
P.S. Ignore all the printf as they are there to check where the program is going wrong.
#include <stdio.h>
#include <string.h>
int main(){
char *p = "hello world", *q = "world", *start;
int i, count = 0;
printf("%c\n", *p);
for (i = 0; i < strlen(p); i++){
printf("p: %c compares with q: %c\n", *p, *q);
if ( *p == *q){ // tried: if ( p == q)
start = p;
printf("start: %s\n", start);
while (*p == *q){ // tried: while ( p == q)
printf("p: %c compares with q: %c\n", *p, *q);
count ++;
p ++;
q ++;
if ( count == strlen(q) ){
printf("Found it\n");
return *start;
}
}
}
p ++;
}
printf("Not Found\n");
return 0;
}
As soon as it hits the w it prematurely exit out of the loop. I am not sure why its doing this? This is my question.
Output:
p: h compares with q: w
p: e compares with q: w
p: l compares with q: w
p: l compares with q: w
p: o compares with q: w
p: compares with q: w
Not Found
Edit:
gcc -Wall filename.c Compiler is not giving me any kinds of warnings/errors.