If we pass an array to the function, we iterate through it until "p" is a nullptr. But this should never happen because the address after the last element that has value 0 in the array is not a nullptr(doesn't have value zero). How is this possible?
int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-ter minated array of char (or to nothing)
{
int count = 0;
while (p) {
if (*p==x)
++count;
++p;
}
return count;
}
The code is wrong.
The while
condition needs to be
while(*p)
instead of
while(p)
EDIT: Found it in the errata also - http://www.stroustrup.com/Tour_printing2.html
pp 11-12: The code for count_if() is wrong (doesn't do what it claims to), but the points made about the language are correct.
That function is not valid. Your version of the book contains an error. The correct version tests *p
in the while
condition.
int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
int count = 0;
while (*p) {
// ^----------------- You omitted this asterisk.
if (*p==x)
++count;
++p;
}
return count;
}
Update: the code apparently changed a little bit between printings, and the errata for the first printing mentions an error related to this function. Hat tip to @BenVoigt.
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