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?
because
getline
puts\n
in last character.see in
getline
functionif(c=='\n'){s[i]=c;++i; }
Also
p
is allocated to block of length ofline
so that line could be copied to to becauseline
is used to store subsequent characters line, if it is not copied all line will be lost.