1

I am fairly new to the concept of structs in C, and have run into a problem. I have looked for any similar problems posted here, but cannot find any. What I am trying to do is pass a variable in an array of structs as a parameter in a function, as so:

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

2 Answers 2

2

There are a few problems here.

  1. You cannot nest functions inside other functions like you can in languages like Java, C#, Python.
  2. You are passing the struct array incorrectly.
  3. Your main declaration is incorrect.

You want code something like this:

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;
}

Note that you are missing initialization of sTable.

What's more you really ought to pass the length of the array as a parameter to maxAverage. That will then allow you more flexibility to use arrays of any length.

Sign up to request clarification or add additional context in comments.

2 Comments

The references to .value in maxAverage should be .average, I believe.
@jwodder Thanks, I just moved the code around in the editor, didn't try to compile it.
0

First of all, you can't declare or define a function inside another function, so move maxAverage outside of main (which, incidentally, should return int, not void). Secondly, given an array of structs, you can't just automatically create an array of the values from a certain field of the structs; if you want to, you would have to manually declare a separate array of (in this case) floats and then copy over the average fields one by one. A simpler way would be to simply pass sTable itself to maxAverage and have maxAverage only operate on the average fields of the structs in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.