-5
#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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

0

First of all, this line

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

should look like

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

because as per this discussion we need not to cast the return value of malloc() and family in C..

That said, to break down the statement,

  1. First, temp = realloc(data, capacity*sizeof(double)) gets evaluated. This statement reallocates data to have a memory allocated equal to the size of capacity*sizeof(double) bytes. The returned pointer is stored to temp.

  2. Then essentially the whole statement reduces to if (! (temp)). This check for the success of the realloc() call by checking the returned pointer against NULL.

    • If realloc() failed, it returned NULL, and the if will evaluate to TRUE, so the program will execute exit(1); and get over.

    • If realloc() is a success, temp will have a non-NULL pointer, thereby, the if check will fail and the program will continue normally.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261