0

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Assaf
  • 1,112
  • 4
  • 14
  • 35

2 Answers2

2
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.

The Mighty Programmer
  • 1,242
  • 12
  • 23
  • so line[len] is the place of the last char of the chars array, which is the string? @haccks – Assaf Dec 14 '13 at 10:08
  • Last char which is `'\0'` will go to `line[len-1]`. – haccks Dec 14 '13 at 10:15
  • 1
    If you see `getline` defination then analyze : `s[len-1]='\n'` and `s[len]='\0'`.. logically if you include then `\n` in string definition then your length become `len` if not then `len-1` . In above code, you are not including `\n` in string, so your length become `len-1` home of `\0` – The Mighty Programmer Dec 14 '13 at 10:15
1

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()?