/* File: realloc.c

   Store user input in an array.
*/

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

#define START_SIZE 5 ;

main() {
   int *A, *temp ;
   int limit, n, r, input, i ;


   /* Allocate some space for A initially */

   limit = START_SIZE ;
   A = (int *) malloc (limit * sizeof(int)) ; 
   if (A == NULL) {
      fprintf(stderr, "malloc() failed!\n") ;
      exit(1) ;
   }


   /* Main loop */

   n = 0 ;
   printf("Enter numbers, 1 per line. End with ctrl-D\n") ;
   while(1) {
      printf("? ") ;  
      r = scanf("%d", &input) ;
      fflush(stdin) ;

      /* Anything entered? */
      if (r < 1) break ;

      /* Get more space for A */
      if (n >= limit) {

	 printf("DEBUG: reallocating A ... \n") ;

	 limit = 2 * limit  ;
	 temp = realloc(A, limit * sizeof(int)) ;
	 if (temp == NULL) {
	    fprintf(stderr, "realloc() failed!\n") ;
	    exit(1) ;
	 }
	 A = temp ;
      }

      A[n] = input ;
      n++ ;
   }


   /* Trim A down to size */
   temp = realloc(A, n*sizeof(int) ) ;
   if (temp == NULL) {
      fprintf(stderr, "Really strange realloc() failure!\n") ;
      exit(1) ;
   }
   A = temp ;


   printf("\nContents of the array A:\n") ;
   /* Print array just for show */
   for (i = 0 ; i < n ; i++) {
      printf("%2d ", A[i]) ;
   }
   printf("\n") ;
}
