Zzz
Zzz

Reputation: 3025

How to determine the length of an array of structs inside another struct

I am trying to write a function that acts on a member of a struct that is in an array of structs that is a member of another struct :). The first thing I need to do is find out the length of the array of structs, but I keep getting the error expression must be class type.

What would be the appropriate way for me to get the length of this array? (PS. The function has to take the Student structure as an argument.)

The structs:

struct Class
{
    string title; 
    int units;
    char grade;

};
struct Student
{
    string name;
    double gpa;
    Class classes[500];
};

My function looks something like this:

void gpaCalculate (Student s)
{
    int size = s.classes.size() ;
    //Lots of awesome code
}

Upvotes: 0

Views: 226

Answers (3)

Robert Cooper
Robert Cooper

Reputation: 1270

In answer to the question "How do I determine the length of an array?", use (sizeof(array) / sizeof(*array)), as in

void gpaCalculate (Student s)
{
    int size = (sizeof s.classes) / sizeof(*s.classes);
    //Lots of awesome code
}

Note: this will not work with variable-length array parameters. In answer to the question "How should I store a list of items in C++", generally you should use a vector. Vectors tend to be easier to work with than arrays. For example, vectors unlike arrays can change size.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

The code

struct Student
{
    string name;
    double gpa;
    Class classes[500];
};

indicates that a Student can attend to maximum 500 classes, and that this is some school assignment where you are expected/required to use raw arrays, instead of the otherwise much more appropriate std::vector.

First, the magic number 500 should be made a constant, like so:

int const maxClasses = 500;

Then in each Student object you need to store the actual number of classes this student attends to:

struct Student
{
    string name;
    double gpa;
    int nClasses;
    Class classes[maxClasses];

    Student()
        : name(), gpa( 0.0 ), nClasses( 0 ), classes()
    {}
};

The constructor ensures that gpa and nClasses will be zeroed.

Since they're of built-in types that's otherwise not guaranteed (per the principle that you don't pay for what you don't use, so it's your decision).

Upvotes: 3

Taylor Jones
Taylor Jones

Reputation: 163

What if you changed the structures to C++ classes? Then you could create a function to access the size of the array of Classes. you could easily call the gpaCalulate function as a function of the Class class.

Upvotes: 0

Related Questions