将struct成员传递给c中的函数

0 c struct

我有这个文件,并在c中输入结构数组.但是我在将struct成员传递给函数时遇到了问题.错误:甚至没有指针或数组值与第58行中的下标有关.我是c的新手并且坚持这个问题一个星期.

代码:

#include <stdio.h>
#include <math.h>
#define SIZE 100

typedef struct list{
  int counter;
  int year;
  double maxrain;
  double rank;
} data;

double avg (struct list s, int count);

int main()
{
  data a[SIZE];
  struct list s;
  double sum = 0;
  int totalFile = 1;        // according to number of csv file
  int z, i;
  char fName[16];
  FILE*fpt;

  double mean;

  /* reading multiple file */
  for (z=1; z<=totalFile; z++)
  {
    sprintf(fName," ",z);
    fpt = fopen(fName,"r");

    if(fpt == NULL){
      printf("Error opening %s\n",fName);
      return(-1);
    }

    printf("---Reading from file %d---\n", z);
    sum = 0;
    i = 0;
    while(i <= SIZE && fscanf(fpt, "%d%*c%d%*c%f%*c%f", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank) != EOF){
      sum = sum + a[i].maxrain;
      i++;  
    }
    mean = avg(a[i].maxrain, i);
    printf("%f", mean);

    return 0;
  }
}

double avg(struct list s , int count)
{
  double ave;
  int i = 0;

  for(i=0; i<count; add += s.maxrain[i++]);
  ave = add/count;

  return ave;
}
Run Code Online (Sandbox Code Playgroud)

alk*_*alk 5

如果您已经告诉编译器告诉您可能的警告的最大值,那么编译器会指向您的几个问题.对于gcc,这样做的选项是-Wall -Wextra -pedantic.

但现在针对问题详细说明:

这里

sprintf(fName, " ", z);
Run Code Online (Sandbox Code Playgroud)

缺少转换说明符.代码应该如下所示:

sprintf(fName, "%d", z);
Run Code Online (Sandbox Code Playgroud)

另外的sprintf()是取消保存,因为它可能会溢出目的地"串".snprintf()改为使用:

snprintf(fName, "%d", sizeof(fName), z);
Run Code Online (Sandbox Code Playgroud)

以下扫描命令使用%f哪个预期的float,但是已经double传入.

fscanf(fpt, "%d%*c%d%*c%f%*c%f", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank)
Run Code Online (Sandbox Code Playgroud)

使用%lf扫描双打:

fscanf(fpt, "%d%*c%d%*c%lf%*c%lf", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank)
Run Code Online (Sandbox Code Playgroud)

这个

mean = avg(a[i].maxrain, i);
Run Code Online (Sandbox Code Playgroud)

应该

mean = avg(a[i], i);
Run Code Online (Sandbox Code Playgroud)

最后,add缺少声明/定义avg().


作为将变量声明为服务器作为数组索引的说明:

数组指示总是正数,因此使用有符号变量没有意义.

此外,还不确定一个或另一个整数类型的宽度,因此不能保存每个用于寻址内存.在寻址数组元素(以及使用此存储器)时保持在保存方面使用size_t,这是C标准保证的宽无符号整数,足以处理所有机器的内存(并且使用最大可能的数组元素).