Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function in K&R example returning wrong string length?

Tags:

arrays

c

string

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?

like image 414
Spellbinder2050 Avatar asked May 17 '26 07:05

Spellbinder2050


1 Answers

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 a break to exit from a loop when the rightmost non-blank, non-tab, non-newline is found.

/* trim:  remove trailing blanks, tabs, newlines */
[... code ...]

strlen returns 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).

like image 80
jamesdlin Avatar answered May 18 '26 21:05

jamesdlin