mardi 19 janvier 2016

Can you tell me specific what this program is doing?

#include stdio.h
#include <stdlib.h>
#include <ctype.h>
#define CAPACITY_INCREMENT 6
double average(double data[], int count)
  {
   double sum = 0.0;
   int i;
   for(i=0;i<count;sum+=data[i++]);
   return sum/count;
  }

int main(void)
  {
    double *data = NULL;
    double *temp = NULL;
    int count = 0;
    int capacity = 0;
    char answer = 'n';

   do
    {
      if(count == capacity)
       {
          capacity += CAPACITY_INCREMENT;
          if(!(temp = (double*)realloc(data, capacity*sizeof(double))))
         {
            printf("Error allocating memory for data values.\n");
            exit(1);
         }
         data = temp;
       }

       printf("Enter a data value: ");
       scanf(" %lf", data + count++);
       printf("Do you want to enter another (y or n)? ");
       scanf(" %c", &answer, sizeof(answer));
     } while(tolower(answer) != 'n');

    printf("\nThe  average of the values you entered is %10.2lf\n", average(data, count));
    free(data);
    return 0;
   }

I am a beginner in C and one of my friend who is helping me sent me this code, I understood that is printing the average of given number but I don't know what some syntaxes are doing like:

  if(!(temp = (double*)realloc(data, capacity*sizeof(double))))"

Can you explain how this is working step by step?

Aucun commentaire:

Enregistrer un commentaire