Hi there,
I'm experimenting with one of the functions in the K&R C Programming Language book and using pointers to write the strindex function rather than array notation. I have a strange problem that if I include a printf() statement at either of the two points in my code below then the function returns the correct index (6 in this case), but if I leave the printf() statements out then the function returns -1.
I really can't see why this should make any difference at all and would be grateful for any clarification. Here's my code:
#include <stdio.h>
int strindex(char *a, char *b) {
char *pa;
char *astart = a;
char *pb = b;
int len;
while(*pb++ != '\0')
len++;
while(*a != '\0') {
pa = a;
pb = b;
for(;*pb != '\0' && *pa == *pb; pa++, pb++)
;
if(len > 0 && *pb == '\0') {
return a - astart;
}
//printf("%c\n", *a);
a++;
}
//printf("%c\n", *a);
return -1;
}
int main() {
char *a = "experiment";
char *b = "me";
printf("index is %d\n", strindex(a, b));
return 0;
}
Many thanks
Joe