The error
When you call your function in main()
:
AthleticContest(subject[2]);
you pass as argument a single person
, which is the third element of your array (the element with index 2). So the compiler understands that you try to pass this object of type person
.
But your function's parameter is declared to be of type array of undetermined size (i.e. person[]
). C++ treats such array arguments as if they were a pointer (to their first element), so like person*
.
This is why you get this error message: these types are incompatible
The solution
To get rid of this error, a solution would be to pass a pointer to a subject
, for example:
AthleticContest(&subject[2]); // passes the pointer to the third element
// or
AthleticContest(subject); // passes the pointer to the first element of the original array
However, be very careful, because your function has a very risky design: you expect the argument to be a pointer to an array of at least 3 consecutive elements. So if you call it with &subject[8]
, it would try to access subject[10]
which would be out of bounds. If you'd call with &subject[2]
it would work with garbege information, since you have initalized only the first two elements, and not the 3rd, 4th and 6th.
A better solution
It is not clear, why you do the constest just with 3 elements. A better option would be the caller to say how many contestant shall be used (the caller know the size of the array).
In main()
:
AthleticContest(subject, 2); // 2 is the number of contestants in array
Your function would be defined as:
int AthleticContest(person subjects[], int participants)
{
cout << "Athletic Contest!!!" << endl << endl;
for (int hh = 0; hh < participants; hh++)
...
for (int hh = 0; hh < participants; hh++)
...
}
A much better solution
You'd better go for std::vector
instead of C++ arrays. They can behave like arrays:
vector<person> subject(2); // create a vector of 2 items
subject[0].athletic = 5;
...
But they are much more convenient because they can have a dynamic size and grow as you add new participants:
person hbolt = {4, 2, 1, 0};
subject.emplace_back (hbolt); // one more participant
AthleticContest(subject);
Your function could get the vector by reference or by value. Let's take by reference, since you intend to modify its content and could possibly want this modified data after the return:
int AthleticContest(vector<person> &subjects)
{
...
}
The big advantage, is that you can always know the size of the vector:
for (int hh = 0; hh < subjects.size(); hh++)
...
Here is an online demo.
Of course, if you don't want to take all the participants in the vector, you'd have to think about your function's argument(s): would you prefer a second argument n and always take the n first elements of the vector ? Or would you prefer n participants but start at an arbitrary offset ? In both case, you'd be wise to check that your indexing never goes out of bounds.