gpt4 book ai didi

c - 将结构成员传递给 c 中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:41 25 4
gpt4 key购买 nike

我有这个文件并将其作为结构数组输入到 c 中。但是我在将结构成员传递给函数时遇到问题。错误:第 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;
}

最佳答案

如果您告诉编译器告诉您最多可能的警告,编译器会向您指出此处的几个问题。对于 gcc,这样做的选项是 -Wall -Wextra -pedantic

但现在要详细说明问题:

这里

sprintf(fName, " ", z);

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

sprintf(fName, "%d", z);

还有 sprintf()未保存,因为它可能会溢出目标“字符串”。使用 snprintf()相反:

snprintf(fName, "%d", sizeof(fName), z);

以下扫描命令使用 %f,它需要 float ,但传入了 double

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

使用 %lf 扫描 double :

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

这个

mean = avg(a[i].maxrain, i);

应该是

mean = avg(a[i], i);

最后 avg() 中缺少 add 的声明/定义。


关于向服务器声明变量作为数组索引的注意事项:

数组索引总是正数,因此为此使用带符号的变量没有意义。

另外一个或另一个整数类型的宽度是不确定的,所以使用 every 来寻址内存是不节省的。为了在寻址数组元素(以及使用此内存)时保持保存状态,请使用 size_t,C 标准保证它是一个无符号整数,宽度足以寻址所有机器的内存(并且这是最大可能的数组元素)。

关于c - 将结构成员传递给 c 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19853714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com