在函数returnAvg中,我需要代码返回一个数组,但它只返回第一个不熟悉指针的元素。 ar [0]是完全平均的,但是ar [1]总是0为什么会发生这种情况?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double returnAvg(int allTest[2][2],int students,int test);
int main ()
{
int students = 2, test = 2, i,j;
int allTest[students][test];
double ar[students];
for(i = 0; i < students; i++){
for(j = 0; j < test; j++){
printf("Student [%d] test [%d] score was> ", i + 1, j + 1);
scanf("%d", &allTest[i][j]);
}
}
*ar = returnAvg(allTest, students, test);
for(i = 0;i<students;i++){
printf("\nthe average score of student[%d] is : %.2lf\n",i+1, ar[i]);
}
return 0;
}
double returnAvg(int allTest[2][2],int students,int test){
int i,j;
double avg[students];
for(i=0;i<students;i++){
int sum = 0;
for(j=0;j<test;j++){
sum += (allTest[i][j]);
}
avg[i] = (float)sum/test;
}
return *avg;
}
答案 0 :(得分:3)
您正在尝试将本地数组返回到其他错误的函数。
当你的函数返回其本地内存时...
您需要为该数组使用Malloc,然后返回其指针
double* returnAvg(int allTest[2][2],int students,int test){
int i,j;
double *avg;
avg = malloc(sizeof(double) * students);
for(i=0;i<students;i++){
int sum = 0;
for(j=0;j<test;j++){
sum += (allTest[i][j]);
}
avg[i] = (float)sum/test;
}
return avg;
}
使用后别忘了释放内存:)
答案 1 :(得分:0)
抱歉,无法在C中返回数组。
您可以返回包含数组的结构,但这仅适用于固定大小的数组。
这里最好的解决方案是要求来电者留出空间:
void computeAvg( int students, int test, int input[students][test], double output[students])
{
// ...
output[i] = (double)sum/test;
// ...
}
在主叫代码中:
double ar[students];
computeAvg(students, test, allTest, ar);
我重新排列了函数参数的顺序,以便您可以编写正确的维度int input[students][test]
,而不是放置[2][2]
,这对student
和{{1}的其他值都是错误的}。
另一种可能的解决方案是一次只计算一个学生的平均值,然后返回test
。然后你的main函数在循环中执行:
double