Added example with variable arrays.
[C-Programming-Examples.git] / ex_5-7.c
blob38d738dd2c3903e555a9f3ce9723cb795f72b3e5
1 #include <stdio.h>
2 #include <string.h>
4 #define MAXLINES 1000 // max number of lines in buffer
5 #define MAXLEN 1000 // max length of individual lines
7 // declare lines as an array of array of char
8 // iow: create the maximum size empty buffer in global scope
9 char lines[MAXLINES][MAXLEN];
11 /* print contents of array */
12 void print_sparse_array(char s[][MAXLEN])
14 int i, j;
15 for(i = 0; i < MAXLINES; i++)
17 int found = 0;
18 for(j = 0; j < MAXLEN; j++)
20 if(s[i][j] != '\0') { found++; }
22 if(found > 0)
24 printf("%d:\t", i);
25 for(j = 0; j < MAXLEN; j++)
26 printf("%c", s[i][j]);
27 printf("\n");
30 printf("\n");
33 /* From K&R Page 29 */
34 int getline(char s[], int lim)
36 int c, i;
37 for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
38 s[i] = c;
39 if (c == '\n')
40 s[i++] = c;
41 s[i] = '\0';
42 return i;
48 reads input lines from stdin and stores each line in buffer named lines
51 int readlines(char lines[][MAXLEN], int maxlines)
53 int len, nlines = 0;
55 while((len = getline(lines[nlines], MAXLEN)) > 0)
56 if(nlines >= maxlines) // when buffer full, return
57 return -1;
58 else
59 lines[nlines++][len - 1] = '\0'; // delete newline
60 return nlines;
63 int main()
65 int length = readlines(lines, MAXLINES);
66 printf("Number of Lines Stored: %d\n", length);
67 print_sparse_array(lines);
68 return 1;