home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap08 / total.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-04-05  |  1.1 KB  |  42 lines

  1. /* total.c  -- how to build an array on the fly    */
  2.  
  3. #include <stdio.h>         /* for NULL   */
  4. #include <malloc.h>        /* for size_t */
  5.  
  6. main()
  7. {
  8.     int *iptr, count = 0, i, total;
  9.     size_t bytes = sizeof(int);
  10.  
  11.     /* Start the array with room for one value. */
  12.     if ((iptr = malloc(bytes)) == NULL)
  13.         {
  14.         printf("Oops, malloc failed\n");
  15.         exit(1);
  16.         }
  17.  
  18.     printf("Enter as many integer values as you want.\n");
  19.     printf("I will build an array on the fly with them.\n");
  20.     printf("(Any non-number means you are done.)\n");
  21.  
  22.     while (scanf("%d", &iptr[count]) == 1)
  23.         {
  24.         ++count;
  25.         /* Enlarge the array. */
  26.         if ((iptr = realloc(iptr,bytes*(count+1))) == NULL)
  27.             {
  28.             printf("Oops, realloc failed\n");
  29.             exit(1);
  30.             }
  31.         }
  32.     total = 0;
  33.     printf("You entered:\n");
  34.     for (i = 0; i < count; i++)
  35.         {
  36.         printf("iptr[%d] = %d\n", i, iptr[i]);
  37.         total += iptr[i];
  38.         }
  39.     printf("\nTotal: %d\n", total);
  40.     return (0);
  41. }
  42.