Hi!
Please, help me to get through this function.
Here is what I do and don't understand in it.
First the function together with get_line function.
Code:
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while ((len = get_line(line, MAXLEN)) > 0)
{
if (nlines >= maxlines || (p = alloc(len)) == NULL)
{
return -1;
}
else
{
line[len - 1] = '\0'; /* delete newline */
strcpy(p, line);
lineptr[nlines++] = p;
}
}
return nlines;
}
/* getline: read a line into s, return length */
int get_line (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;
}
Let's assume the first input of "Hello world".
Readlines()
1) defines pointer to char p, and character array line[]
2) first iteration of while loop:
- calls getline()
- if there was an input getline() returns the value
of i, which is assigned to the variable len
- nlines is set to 0, it's a counter (index)
- loop checks if len is bigger then 0; len = 12
(Hello world + '\n' + '\0'), condition is true
- if statement allocates memory to p by calling alloc
function
- then if statement checks its conditions; they are
false
- move to else part, and set line[11] to '\0'
- copy bytes from line to p by strcpy(p, line)
- make lineptr[0] point to p[0], now
the memory stored for whatever lineptr should point to
is filled with "Hello world"
- nlines is incremented and is now equals 1
- loop has finished its first iteration
3) second iteration of while loop starts the processes all
over again, by calling get_line function, which in turn
overwrites all values stored in line[], and after get_line
is done with its job, line[] has new input text stored in
it. Then goes the same process as in the first iteration.
By overwriting values of line[] the get_line allows to get
a few input lines.
Is this assumption correct?
Thanks!