This is from page 65 in K&R. Description says that this function returns the string length. Here is the code:
int trim (char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
return n;
}
It looks like it should be returning n+1. Is the null character not considered part of the string?
Example:
char s[4];
s[0] = c, s[1] = a, s[2] = t, s[3] = '\0';
Wouldn't this mean the string size is 3 and that there are 3 usable elements? That function would return 2, which is incorrect.
Also, what is string length defined as then?
You are correct that the given implementation of trim does not return the length of the resulting string.
It is not necessarily incorrect, however.
My copy of K&R (2nd) edition says:
The following function,
trim, removes trailing blanks, tabs, and newlines from the end of the string, using abreakto exit from a loop when the rightmost non-blank, non-tab, non-newline is found./* trim: remove trailing blanks, tabs, newlines */ [... code ...]
strlenreturns the length of the string....
Nowhere does it say what trim's expected return value is meant to be. While I agree that its actual return value is unintuitive, it's not necessarily wrong since we aren't told how it's supposed to behave.
Also, you may wish to look at the errata for K&R's The C Programming Language (this example is not listed).
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