I'm trying to read input from stdin into an array of pointers, by parsing it into lines(each pointer represents a line). When I try to print them, however, it only prints the first one. I cannot see what the problem is with the rest of them. (This is part of an exercise from K&R). Also, I am aware of the memory leak, but it does not pose a concern for me now.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000
char *lineptr[MAXLINES];
int readlines(char *[], int);
void writelines(char *[], int);
main(int argc, char *argv[])
{
int i, nlines;
for (i = 0; i < MAXLINES; ++i)
{
lineptr[i] = malloc(MAXLINES * sizeof(**lineptr));
}
nlines = readlines(lineptr, MAXLINES);
writelines(lineptr, nlines);
return 0;
}
int readlines(char *lineptr[], int nlines)
{
int num;
char *c_ptr = *lineptr;
for (num = 0; (*c_ptr = getchar()) != EOF; ++c_ptr)
{
if (*c_ptr == '\n')
{
*c_ptr = '\0';
c_ptr = *++lineptr;
if (++num >= nlines)
{
return num;
}
}
}
*c_ptr = '\0';
return num;
}
void writelines(char *lineptr[], int nlines)
{
while (nlines--)
{
printf("%s\n", *lineptr++);
}
}