/* reads lines of text from the standard input. Treats each line as an integer
 * by calling <var>atoi</var>, and stores each integer in a
 * dynamically-allocated "array"
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 100
#define INITSIZE 2

/* getline() reads one line from standard input and copies it to line array
 * (but no more than max chars).
 * It does not place the terminating \n in line array.
 * Returns line length (0 for empty line), or EOF for end-of-file.
 */
int getline(char line[], int max)
{
  int nch = 0, c;
  max = max - 1;			/* leave room for '\0' */

  while ((c = getchar()) != EOF) {
    if (c == '\n')
      break;
    if (nch < max) {
      line[nch] = c;
      nch = nch + 1;
    }
  }

  if (c == EOF && nch == 0)
    return EOF;

  line[nch] = '\0';
  return nch;
}

int main()
{
  char line[MAXLINE];
  int *ip;
  int nalloc, nitems;

  nalloc = INITSIZE;
  ip = (int *) malloc(nalloc * sizeof(int));	/* initial allocation */
  if (ip == NULL)	{
    printf("out of memory\n");
    return -1;
  }

  nitems = 0;
  
  while (getline(line, MAXLINE) != EOF) {
    if (nitems >= nalloc) {			/* increase allocation */
      int *newp;
      nalloc *= 2;
      newp = realloc(ip, nalloc * sizeof(int));
      if (newp == NULL) {
        printf("out of memory\n");
        return -1;
      }
      ip = newp;
    }
    ip[nitems++] = atoi(line);
  }

  printf("Allocated %d items, initialize %d items\n", nalloc, nitems);
  return 0;
}
