char *strchr( const char *s, int c );
I understand that strchr locates the first occurrence of character c
in string s
. If c
is found, a pointer to c
in s
is returned. Otherwise, a NULL
pointer is returned.
So why does below code outputs num to strlen(string) rather than what its designed to do?
num=0;
while((strchr(string,letter))!=NULL)
{
num++;
string++;
}
But this code gives correct output
num=0;
while((string=strchr(string,letter))!=NULL)
{
num++;
string++;
}
I fail to see why assigning the pointer that's returned to another qualified pointer even makes a difference. I'm only just testing if return value is a NULL pointer or not.
string
is a pointer.
In the first example, you just move it right one position, regardless of where (or if!) "letter" was found.
In the second example, every time you find a "letter", you:
a) update "string" to point to the letter, then
b) update "string" again to point just past the letter.