c - 无法将结构数组的变量作为函数参数传递

标签 c struct

我对 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));
}

最佳答案

这里有几个问题。

  1. 您不能像在 Java、C#、Python 等语言中那样将函数嵌套在其他函数中。
  2. 您传递的结构数组不正确。
  3. 您的主要声明不正确。

你想要这样的代码:

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/

相关文章:

c++ - C++中的结构继承与类继承

c - VIM 与你一起完成我

c - 使 C 代码运行得更快

c - c 中的 x -> y 是否与 c#/java 中的 x.y 相同?

c - 通过结构体访问可变长度内存对象是否定义良好?

c - 访问结构中的字符指针字段

C 程序以 -1 (0xFFFFFFFF) 终止,似乎没有任何原因?

C编程: How to extract a particular column from an input file and store in an array

c - 在 C 中返回一组记录

成员的 C 结构顺序