Rewrite
readlines
to store lines in an array supplied by main, rather than callingalloc()
to maintain storage. How much faster is the program?
Here is my solution:
int readlines(char **lineptr, char *storage, int maxlines, int storage_size) {
int len;
int nlines;
nlines = 0;
while((len = _getline(storage, MAXLEN))) {
if(nlines >= maxlines || !(storage_size - len)) {
return -1;
}
else {
storage[len - 1] = '\0';
lineptr[nlines] = storage;
storage += len; // next free space in the buffer supplied by main
storage_size -= len;
nlines++;
}
}
return nlines;
}
Now, the function takes 2 more arguments: a pointer to the array that will store all the read lines and its size. There is no need now to use another array to store the line temporary, I just can pass portions of the storage
to getline
.
The condition !(storage_size - len)
verifies if there is enough space in storage
to store the line that was just read. At each iteration storage
is incremented to point to the next free space in the array and the value of the variables storage_size
is reduced.
(This exercise can be found at page 124 in K&R.)