我在将数组传递给 C 中的函数时遇到问题。我在 main 中声明了数组
然后,在一个函数内部,我填充它。
此时我离开我的函数并将数组传递给带有原型的另一个函数
并尝试访问该数组。
但是,一旦我退出填充数组的初始函数,我将无法访问该数组。它只返回 0.00000 和 nan 的值。
void ReadData(FILE *fpIn, int lines, double *pA );
void MinMaxAvg(double *pA, double *min, double *max, double *avg, int lines);
int main()
{
FILE *fpIn = NULL;
int lines = 0;
double *pA = NULL;
ReadData(fpIn, lines, pA);
double min = 0;
double max = 0;
double avg = 0;
MinMaxAvg(pA, &min, &max, &avg, lines);
printf("%lf %s %lf %s %lf \n", avg, " ", min, " ", max);
return 0;
}
void ReadData(FILE *fpIn, int lines, double *pA )
{
char fName[20];
scanf( "%s", fName);
fpIn = fopen ( fName, "rt");
// fpIn = fopen( "test1.txt", "rt");
if ( fpIn == NULL)
{
printf( "Unable to open: ");
exit(99);
}
//Gets Lines
//int lines=0;
char ch;
while((ch=fgetc(fpIn))!=EOF)
{
if (ch=='\n') { lines++; }
}
// clearerr(fName *fpIn);
fclose(fpIn);
fopen(fName, "rt");
//Makes Array
//double *pA;
pA = (double *)malloc(lines*sizeof(double));
//Fills Array
for (int i=0; i<lines; i++)
{
fscanf(fpIn, "%lf", &pA[i]);
}
for (int i=0; i<lines; i++)
{
printf("%lf \n", pA[i]);
}
}
void MinMaxAvg(double *pA, double *min, double *max, double *avg, int lines)
{
double total = 0;
for (int i=0; i<lines; i++)
{
if ( i==0)
{
*min = pA[0];
*max = pA[0];
}
else
{
if (pA[i] < *min)
{
*min = pA[i];
}
if (pA[i] > *max)
{
*max = pA[i];
}
}
total += pA[i];
}
*avg = (total / (double)lines);
}
有什么建议么?
谢谢!