我对 C 中的结构概念还很陌生,遇到了一个问题。我已经寻找过此处发布的任何类似问题,但找不到任何问题。我想要做的是将结构数组中的变量作为函数中的参数传递,如下所示:
struct Student
{
float average;
int ID;
int grades[5];
char firstName[20], lastName[20];
};
void main(void)
{
struct Student sTable[10];
float maxAverage(float sTable[].average)
{
int i;
float max = 0;
for(i = 0;i < 10; ++i)
{
if(sTable[i].value > max)
{
max += sTable[i].value;
}
}
return max;
}
printf("%f",maxAverage(sTable[].average));
}
最佳答案
这里有几个问题。
- 您不能像在 Java、C#、Python 等语言中那样将函数嵌套在其他函数中。
- 您传递的结构数组不正确。
- 您的主要声明不正确。
你想要这样的代码:
struct Student
{
float average;
int ID;
int grades[5];
char firstName[20], lastName[20];
};
float maxAverage(struct Student sTable[])
{
int i;
float max = 0;
for(i = 0;i < 10; ++i)
{
if(sTable[i].value > max)
{
max += sTable[i].average;
}
}
return max;
}
int main(void)
{
struct Student sTable[10];
//initialize sTable
printf("%f", maxAverage(sTable));
return 0;
}
请注意,您缺少 sTable
的初始化。
此外,您确实应该将数组的长度作为参数传递给 maxAverage
。这样一来,您就可以更灵活地使用任意长度的数组。
关于c - 无法将结构数组的变量作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837738/