9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia04/ex09.c (1153B)
   1 /*    Populates the direction in memory pointed by every element of an array
   2  *    of 10 pointers to float    with 10 numbers entered via stdin.    */
   3  
   4 #include <stdio.h>
   5 #include <stdlib.h>
   6 #include <float.h>
   7 
   8 #define BUFFER_LEN 10
   9 
  10 int main (void)
  11 {
  12     char aux, buffer[BUFFER_LEN + 1];
  13     float *pf[10];
  14     double *sum;
  15     size_t i;
  16 
  17     printf("%d\n", FLT_MAX);
  18     printf("%d\n", FLT_DIG);
  19 
  20     if(!(sum = (double *)calloc(1, sizeof(double))))
  21         return 1;
  22 
  23     /*    Makes every pointer point to a space in memmory with space for one float number    */
  24     for(i = 0; i < 10; i++) {
  25         if(!(pf[i] = (float *)calloc(1, sizeof(float)))) {
  26             for(size_t j = i; j > 0; j--)
  27                 free(pf[j]);
  28 
  29             return 1;
  30         }
  31     }
  32 
  33     /*    Populates the array with user input converted to float, computes the sume of all
  34      *    the converted numbers and then frees the memmory since it's no longer needed    */
  35     for(i = *sum = 0; i < 10 ; i++) {
  36         if(!fgets(buffer, BUFFER_LEN, stdin)) return 2;
  37         *sum += (*pf[i] = strtof(buffer, NULL));
  38 
  39         printf("%p: %5f\n", pf[i], *pf[i]);
  40         free(pf[i]);
  41         while(((aux = getchar()) != 10) && (aux != 13))
  42             putchar(aux);
  43     }
  44 
  45     printf("\nsum:  %5f\n", *sum);
  46 
  47     free(sum);
  48     return 0;
  49 }