/* Example: backward printing of text with pointers Source: K&R2, p108 Modified by Peter Brusilovsky */ #include #include #define MAXLINES 5000 static char *lineptr[MAXLINES]; void copy(char *p1, char *p2); int getline(char *line, int max); int readlines(); void printbackwards(int n); void main() { int nlines; /* counter of input lines read */ nlines = readlines(); printbackwards(nlines); } #define MAXLEN 1000 int readlines() { int len, nlines; char *p, line [MAXLEN]; nlines = 0; while((len = getline(line, MAXLEN)) > 0) { p = (char *) malloc(len+1); copy(p, line); lineptr[nlines] = p; ++ nlines; } return nlines; } void printbackwards(int n) { while(n > 0) { printf("%s", lineptr[n-1]); --n; } } /* getline: read a line into s, return length */ int getline(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; } /* copy: copy 'from' into 'to'; assume to is big enough */ void copy(char *to, char *from) { int i = 0; while((to[i] = from [i]) != '\0') ++i; }