getline function definition in K&R

Viewed 50

The following is getline implementation in K&R on page 29 ,

# define MAXLINE 1000
int getLine(char s[], int lim)
{
    int c ,i ;
    for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c!= '\n'; ++i)
        s[i] = c;
    if(c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
    
}

I don't understand why we need to do "i < lim - 1" here in the for loop. For correct indexing, why doesn't " i < lim " suffice ?

Any help would be much appreciated...

1 Answers

The function is going to build a string (stored in the array specified by the parameter char s[]) that is a sequence of characters terminated with the zero terminating character '\0'.

So one element of the array is reserved for the terminating zero character that is appended to the character array before exiting the function

s[i] = '\0';

For example if the variable lim is equal to 5 then you may enter in the array no more than 4 characters in the range of indices [0, 3]. In this case (if all lim-1 characters will be filled) in the last element of the array there will be written the terminating zero character '\0' at position 4.

Related