能具体说说这个程序是做什么的吗?

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;
   }

我是 C 的初学者,我的一位帮助我的朋友给我发了这段代码,我知道这是打印给定数字的平均值,但我不知道某些语法在做什么,例如:

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

你能解释一下这是如何一步步工作的吗?

首先,这一行

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

应该看起来像

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

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

也就是说,要分解语句,

  1. 首先,temp = realloc(data, capacity*sizeof(double)) 被评估。此语句重新分配 data 以分配等于 capacity*sizeof(double) 字节大小的内存。返回的指针存储到temp.

  2. 然后基本上整个语句减少到 if (! (temp))。通过检查返回的指针是否为 NULL 来检查 realloc() 调用是否成功。

    • 如果realloc()失败,它返回NULL,而if将评估为TRUE,所以程序将执行exit(1);并结束。

    • 如果realloc()成功,temp将有一个non-NULL指针,因此,if检查将失败,程序将正常继续。