Why is *str in the following fragment dereferenced only once? It takes the first character of the string 'a' and keeps incrementing this value until it reaches the end of the ASCII table, contrary to my expectation of dereferencing it on every condition evaluation and resulting in the infinite loop. This behavior does change even if the dereference is moved from the condition to the body of the loop. GCC version 7.4.0 was used to test the code.
int getLen(char *str){
int count=0;
while((*str)++) {
count++;
}
return count;
}
int main(){
char s[]="abc";
printf("length is %d\n",getLen(s));
}
Output: 159
It is dereferenced 159 times, not just once.
The ASCII value of a
is 97
. If you increment that 159
times, you get 0
.
(*str)++
doesn't increment str
, it increments the first character in str
.
It doesn't increase it "until it reaches the end of the ASCII table", it increases until it becomes 0
. If your char
type is signed, that means that it increments it to the maximum of that type, then from the minimum (a negative value) up to 0
.
Typically, char
is signed and 8-bits. In that case, it will increase to 127
, the next value will be -128
and after that it will keep increasing until it becomes 0
.
If you want to use parentheses for clarity, use
while (*(str++))
{
count++;
}
That is the same as
while (*str++)
{
count++;
}
The term (*str)++
is the source of your problem. You have added ()
around *str
, which makes sure that *str
is evaluated first and that value is incremented. It never increments str
. Use *str++
instead.
while(*str++) {
count++;
}
The expression (*str)++
says, dereference str
first, then increment the dereferenced value. It never increments str
itself (the pointer).
So, to answer your question, it's not that str
is being dereferenced only once, it's dereferenced every time in the loop, but it never gets incremented hence the dereferenced memory is same every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With