Link to home
Start Free TrialLog in
Avatar of ctirish
ctirish

asked on

Sorting Structure in C

I am trying to sort a structure in C. I am using one of the fields of the structure as a sort field. The current problem is it won't compile with the temp field of the sort as an integer and the other field being sorted as a array of the structure.
The error I am getting is
Cannot assign "majorteam" to "int" in function main
Cannot cast from "int" to "majorteam" in function main.

I have both the counters for the sort and the temp field defined as integers.

Here is the code:

for (y=0; y<=9; y++)
{
for (x=y; x<=9;x++)
{
if teamone[y].ability > teamone[x].ability)
{
tempteam = teamone[x];
teamone[x] = teamone[y];
teamone[y] = teampteam;
teamone[y] = tempteam;

then a print statement to print the list by ability.

Any help would be appreciated,
Thanks ctirish@aol.com




ASKER CERTIFIED SOLUTION
Avatar of captainkirk
captainkirk

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
captainkirk has it right, I just want to point out that (judging from the error message) majorteam is the name of the struct, not a separate variable:

majorteam teamone[9];

Regardless, the problem is that teamone[n] is of type majorteam, and tempteam is of type int.  So the line
tempteam = teamone[x]; tries to fit a majorteam into an int variable and
teamone[y] = tempteam; tries to fit an int into a majorteam variable.

tempteam needs to be a majorteam, not an int.
Avatar of captainkirk
captainkirk

yeah - sorry - missed that somehow... substitute "majorteam" for "TEAM" in the example...
also, you will be comparing when x == y.  It won't cause a problem but it is sloppy. You may want to clean that up.

Also, why not use a qsort or other given function?
This looks a lot like a class assignment, I assume that's why not to use a pre-built (and tested) sort routine.

If this is not a school project, there's actually quite a lot to improve -
* STL offers much better alternatives to arrays
* 9 appears several places and should be a constant
* as danny_pav mentions, this problem has been solved many times, just grab an existing sort function
Avatar of ctirish

ASKER

Thank you to all who helped. It was in fact a class assignment.
thanks....
I just want to point out that for getting assignment help here at EE, ctirish did everything right - a specific question, detailed error message, and a sample of already tried code.  And an obvious interest in finding an answer, as opposed to just getting free code.

So many people come here just looking for someone to do their homework for them!  Thanks for validating my faith in students!
you could always overload the '=' operator to perform the struct assignment as well. While I'm not sure if you can do this in C, it is possible in C++ via a member function.