【问题标题】:Can you tell me specific what this program is doing? [closed]你能具体告诉我这个程序在做什么吗? [关闭]
【发布时间】:2016-04-24 22:57:13
【问题描述】:
#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))))"

您能逐步解释这是如何工作的吗?

【问题讨论】:

  • scanf(" %lf", data + count++);???这是什么?你能再困惑点吗?
  • 我投票决定将此问题作为离题结束,因为 SO 不是“解释我的代码”网站。
  • 你为什么不简单地给你的朋友打电话/发邮件问问?
  • 因为他不知道怎么解释。很抱歉给您带来不便,我只是需要一些帮助。这不是我的代码。不管怎样,谢谢你。 :)

标签: c if-statement syntax realloc


【解决方案1】:

首先是这一行

 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将有一个非NULL指针,因此if检查将失败,程序将正常继续。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多