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

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