Jump to: navigation, search

My interpretation of this problem was a little different. Since at this point, we're not meant to know how to use multi-dimensional arrays (or, presumably, malloc), I assumed that the authors wanted us to store the entire set of lines in a single, one-dimensional array, and use the pointer arithmetic we just learned to simply move the pointer to the end of each added line, then add the resulting pointer to the lineptr array.

So, I defined a new array to be the maximum allowable size:

char charList[MAXLINES*MAXLEN];

And then my readlines looks like this:

int readlines(char *lineptr[], int maxlines)
{
	int len, nlines;
	char *p, line[MAXLEN];
	p = charList;
	nlines = 0;
	while ((len = getline(line, MAXLEN)) > 0){
		if (nlines >= maxlines)
			return -1;
		else {
			line[len-1] = '\0';  /* delete newline */
			strcpy(p, line);
			lineptr[nlines++] = p;
			p += len;
		}
	}
	return nlines;

}
Personal tools