Hello,
I am pretty new to all this so bear with me. I need to sort these students based on their test scores.
My biggest problem is with my sort function. I am not sure of the syntax to call the items the proper way. I also don't know how to call the function properly as I know that i can't pass a int to a struct. Any suggestions would be helpful.
Also not sure about the z malloc. Just threw that one in there.
Thank you in advance
Code:
struct student{
int id;
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their score*/
int idx = 0;
for (int i = 0; i < n; i++)
{ idx = i;
for (int j = i; j < n; j++)
{
if (students[j] < students[idx]){
idx = j;
}
}
int min;
min = students[idx];
students[idx] = students[i];
students[i] = min;
}
}
int main(){
/*Declare an integer n and assign it a value.*/
int n = 12;
/*Allocate memory for n students using malloc.*/
int *m = malloc(sizeof(int)*n);
int *z = malloc(sizeof(int)*n);
/*Generate random IDs and scores for the n students, using rand().*/
for (int i = 0; i < n; i++)
{
m[i] = rand() % 10 + 1;
}
for (int j = 0; j < n; j++)
{
z[j] = rand() % 101;
}
/*Print the contents of the array of n students.*/
printf("IDs: ");
for (int i = 0; i < n; i++)
{
printf("%d, ", m[i]);
}
printf("\nScores: ");
for (int j = 0; j < n; j++)
{
printf("%d, ", z[j]);
}
/*Pass this array along with n to the sort() function*/
sort(z, n);
/*Print the contents of the array of n students.*/
printf("\n\nSorted:\n\nIDs: ");
for (int i = 0; i < n; i++)
{
printf("%d, ", m[i]);
}
printf("\nScores: ");
for (int j = 0; j < n; j++)
{
printf("%d, ", z[j]);
}
free(m);
free(z);
return 0;
}