First code snippet:
So why does below code outputs num to strlen(string) rather than what its designed to do?
The output may not be strlen(string)
always and will be depend on the input string string
and the character letter
passed to strchr()
. For e.g. if the input is
string = "hello"
letter = 'l'
then the output you will get is 4
which is not equal to the length of string "hello"
. If the input is
string = "hello"
letter = 'o'
then the output you will get is 5
which is equal to the length of string "hello"
. If the input is
string = "hello"
letter = 'x'
then the output you will get is 0
.
The output is actually depends on the position of last occurrence of the character letter
in the input string.
Reason is that there is only one statement which is modifying the position of string
pointer and that statement is
string++;
It is working in this way -
If the character present in the string
, the strchr()
will return a not null value till the time the input string
pointer point to a character on or before the last occurrence of character letter
in the string. Once string
pointer point to one character after the last occurrence of letter
character in the string, the strchr()
will return NULL
and loop exits and num
will be equal to position of the last occurrence of letter
character in the string. So, you will get the output within the range from 0
to strlen(string)
and not strlen(string)
always.
string = "hello", letter = 'e', num = 0
strchr(string, letter) will return not null as 'e' present in input string
num++; string++;
string = "ello", letter = 'e', num = 1
strchr(string, letter) will return not null as 'e' present in input string
num++; string++;
string = "llo", letter = 'e', num = 2
strchr(string, letter) will return null as it does not find 'e' in input string and loop exits
Output will be 2
Second code snippet:
But this code gives correct output
Yes, the reason is the strchr()
returned pointer is assigned to string
pointer. Take the same example as above, assume the input is
string = "hello"
letter = 'l'
strchr(string, letter)
will return the pointer to first occurrence of character l
and it is assigned to pointer string
. So, now the string pointer pointing first occurrence of l
. Which means, now the string
is
string = "llo"
and in loop body you are doing
string++;
which will make the string pointer point to next character to the character returned by strchr()
. Now the string
is
string = "lo"
letter = `l`
and strchr(string, letter)
will return the pointer to character which the string
is pointing to currently as it is matching to character letter
. Due to string++
in the loop body, now the string will point to next character
string = "o"
letter = `l`
and strchr(string, letter)
will return NULL
and loop will exit. num
is incremented as many times as the character letter
found in string
. Hence the second snippet is giving correct output.