mike3 <mi******@yahoo.comwrites:
I did this in a C program, which involves searching for the
occurence of a string in another string:
---
posptr = strstr(MyString, StringToFind);
if(posptr == NULL) return(-1); /* Didn't find it */
return(((int)(StringToFind - &MyString[0]))/sizeof(char)); /* turn
returned pointer into a zero-indexed character offset */
Several comments on that last statement:
* Most importantly, StringToFind and &MyString[0] do not
point within the same array, so the result of the
subtraction is undefined. Fortunately, it seems that
you really just made a small mistake here: I think that
you really want to subtract &MyString[0] from posptr,
not from StringToFind.
* &MyString[0] and MyString have the same type and value,
except in a few specific contexts, and so you might as
well write the latter.
* The cast to int is gratuitous. The result of
subtracting one pointer from another is already a
signed integer type (often int). Casting this result
to int will either have no effect on its value (the
common case) or yield undefined behavior (if the result
is out of the range of int), so there's no point in
doing it.
* Division by sizeof(char) is also gratuitous, because
sizeof(char) is always 1 by definition.
Thus, you can correctly write this statement as simply:
return posptr - MyString;
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x11f6},*p
=b,i=24;for(;p+=!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}