I'm trying to write some code that takes input lines and then outputs the last N lines. But all my code is doing is outputting the last line N times. Here's the code:
So if the input is:Code:#include <stdio.h> int N = 4; const int MAX_LENGTH = 50; int main(int argc, char *argv[]) { char **lines; char *currLine = (char *) calloc(MAX_LENGTH, sizeof (char)); int start = 0; int current = 0; int i = 0; if (argc > 0 && isdigit(argv[1])) { N = argv[1] - '0'; printf("%d\n", N); } lines = (char **) calloc (N, sizeof (char *)); for (i = 0; i < N; i++) lines[i] = calloc(MAX_LENGTH, sizeof (char)); fgets (currLine, MAX_LENGTH, stdin); while (! feof (stdin)) { *(currLine + strlen(currLine) - 1) = 0; if (current == N) { current = 0; start = 1; } else if (start != 0) { if (start == N - 1) { start = 0; } else { start++; } } *(lines + MAX_LENGTH * current) = currLine; printf("%s\n", *(lines + MAX_LENGTH * current)); current++; fgets (currLine, MAX_LENGTH, stdin); } // output lines: for (i = start; i < N; i++) { printf("f[%d]: %s\n", i, *(lines + MAX_LENGTH * i)); } if (start != 0) { for (i = 0; i < start; i++) { printf("f[%d]: %s\n", i, *(lines + MAX_LENGTH * i)); } } free(lines); free(currLine); return 0; }
Line #1
Line #2
Line #3
Line #4
and N = 2, then the output should be:
Line #3
Line #4
What am I screwing up?




Reply With Quote