Understanding code from K&R

286 views Asked by At

I'm reading K&R for my c language course, I have question in function readlines from section 5.6:

/*readlines: read input lines*/
int readlines(char *lineptr[], int maxlines)
{
    int len, nlines;
    char *p, line[MAXLEN];

    nlines=0;
    while ((len=getline(line, MAXLEN))>0) //getline gets a line of chars and return its 
                                          //length. if the length is negative,
                                          // no line exits.
        if (nlunes>=maxlines || (p=alloc(len))==NULL) //alloc allocates storage for input
           return -1;
        else{
            line[len-1]='\0' //**THIS IS THE PART I DON'T UNDERSTAND**
            strcpy(p,line); //copies line into p (strings)
            lineptr(nlines++)=p;
            }
    return nlines; /*return number of lines we could read*/

So this function is part a sorting function that sorts an array of character lines in lexicographical order using qsort and pointers.

I don't understand particularly what following line does

line[len-1]='\0' //**THIS IS THE PART I DON'T UNDERSTAND**

Why do we have to delete "previous line" or "new line"?

Also, following isn't clean either:

p=alloc(len)

I understand we allocate storage for p which is a pointer. So we allocate appropriate storage for the length of the line in the memory. Is that correct?

2

There are 2 answers

3
The Mighty Programmer On BEST ANSWER
line[len-1]='\0'

because getline puts \n in last character.

see in getline function if(c=='\n'){s[i]=c;++i; }

Also p is allocated to block of length of line so that line could be copied to to because line is used to store subsequent characters line, if it is not copied all line will be lost.

1
AudioBubble On

Does, why do we have to delete "previous line" or "new line"?

We don't. This is not lineptr[len - 1], but line[len - 1]. It NUL-terminates the string, as C strings are expected to be NUL-terminated.

so we allocate appropriate storage for the length of the line in the memory?

Yes, presumably, although I don't know what exactly alloc() does. Perhaps it's a typo (you have quite a few of them in the code), and you actually meant to write malloc()?