Added example with variable arrays.
[C-Programming-Examples.git] / ex_5-13.c
blob79c430233b3866d7219f3745d9e2b32425afafad
1 #include <stdio.h>
2 #include <string.h>
3 #include <ctype.h>
4 #include <stdlib.h>
6 #define DEFLINES 10
7 #define MAXLENGTH 1000
9 void error(const char *err)
11 fprintf(stderr, "ERROR: %s\n", err);
12 exit(EXIT_FAILURE);
15 int getline(char s[], int limit)
17 int i, c;
18 for(i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; i++)
20 s[i] = c;
22 if(c == '\n'){ s[i++] = c; }
23 s[i] = '\0';
24 return i;
27 char *dupstr(const char *in)
29 char *str = malloc(strlen(in)+1);
30 if(str)
32 strcpy(str, in);
34 return str;
37 int main(int argc, char *argv[])
39 int i, j, lines = DEFLINES;
40 char **buff;
41 char buffer[MAXLENGTH];
42 if(argc > 1)
44 lines = atoi(argv[1]);
45 lines = -lines; // input as negative - fixed that here
46 if(lines < 1) { error("Incorrect Input"); }
48 buff = malloc(sizeof *buff * lines);
49 if(!buff) { error("Could not allocate enough memory"); }
50 for(i = 0; i < lines; i++)
52 buff[i] = NULL;
55 int current_line = 0;
56 do {
57 getline(buffer, sizeof buffer); // get line and store in buffer
58 if(!feof(stdin))
60 if(buff[current_line])
61 free(buff[current_line]);
63 buff[current_line] = dupstr(buffer);
64 if(!buff[current_line])
66 error("Out of Memory.");
68 current_line = (current_line + 1) % lines;
70 } while (!feof(stdin));
71 for( i = 0; i < lines; i++)
73 j = (current_line + i) % lines;
74 if(buff[j])
76 printf("%s", buff[j]);
77 free(buff[j]);
80 return EXIT_SUCCESS;