在函数 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;
}
最佳答案
您试图将局部数组返回给其他错误的函数。
当你的函数返回时,它的本地内存消失了..
您需要对该数组使用 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;
}
不要忘记在使用后释放内存 :)
关于c - 数组函数只返回第一个元素,我需要整个数组。请帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598699/