It seems like this code is one-step away from working.. but down (in lines 37-44) *lineptr seems to be 'losing' its value. i.e. it successfully prints in the printf on line37, then seems empty in the printf on line42)
Code:
#include <stdio.h>
#define N 10 /*default lines of input to print*/
#define MAXLINES 5000
char *lineptr[MAXLINES];/*pointers to text lines*/
void writelines(char *lineptr[], int nlines);
main(int argc, char *argv[]) {/* prints the last n ("tail -n") lines of input with command line option*/
int n=0,nlines;/*number of input lines read*/
if (*++argv!='\0' && **argv=='-'){
n=(atoi(*argv))*-1;
}
if ((nlines=readlines(lineptr,MAXLINES,n)) >= 0) {
writelines(lineptr,nlines);
return 0;
}
else {
printf("error:input too big to sort \n");
return 1;
}
}
#define MAXLEN 1000 /*max length of any input line */
int getline(char *, int);
char *alloc(int); /* return pointer to n characters */
int readlines(char *lineptr[], int maxlines, int n) { /*readlines: read input lines into array*/
int len, nlines,j=0;
char *p, line[MAXLEN];
nlines=0;
while ((len=getline(line,MAXLEN))>1)
if (nlines >= maxlines || (p = alloc(len)) == NULL)
return -1;
else {
line[len-1]='\0'; /*delete newline*/
strcpy(p,line);
*lineptr=line;
printf("%s", *lineptr++); /*something seems wrong here..*/
nlines++;
}
while (j<(n>0? n : N)){/*now move pointer back (n or (default) N) places for printing*/
*lineptr--;printf("%s", *lineptr); /*now *lineptr is empty ?*/
j++;
}
printf("%s", *lineptr);
return nlines;
}
/* getline: get line into s, return length */
int getline(char s[], int lim){
int c, i=0;
while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n)/* return pointer to n characters */
{
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
allocp += n;
return allocp - n; /* old p */
} else /* not enough room */
return 0;
}
/*writelines: write output lines */
void writelines(char *lineptr[], int nlines) {
while(*lineptr != '\0')
printf("%s\n test",*++lineptr);
}