This is the function I am currently working on, which is very similar to a qsort function. This function returns true if the array is sorted, and false if it is not. The thing I am struggling with is figuring out how to go through the array and call the comparison function given as a parameter.
My main goal is to compare each adjacent value of the array, and if it is > 0, return false. (Note: This is because my comparision functions are like the qsort function, returning 1 if the first value is greater, -1 if less, 0 if same).
1.) How would I call the compar function if the parameters are void? Also, how would I call on the array "stu" each time and compare each part (ID, firstname, lastname)? Would I need 3 if statements?
bool areStudentsSorted(Student * stu, int numelem, int (*compar)(const void *, const void *)) {
for (int i = 0; i <= numelem; i++){
if (compar(i,i+1) > 0){ <- incorrect
//stuck
return true;
}
Here are two ways of calling the function
if (!areStudentsSorted(stu, numelem, compareFirstName)) {
return EXIT_FAILURE;
}
if (!areStudentsSorted(stu, numelem, compareLastName)) {
return EXIT_FAILURE;
This is an example of a comparison function
int compareLastName(const void * p1, const void * p2)
{
const Student *stu1, *stu2;
stu1 = p1;
stu2 = p2;
return strcmp(stu1->lastname, stu2->lastname);
}
And finally, this is the struct, Student
typedef struct
{
int ID;
char firstname[NAME_LENGTH] ;
char lastname[NAME_LENGTH] ;
} Student;
//stuckshould be short-circuitreturn false, andcomparshould takingstu+i, stu+i+1. Usuallycompardoesn't need to deal with null, since all elements are in an array.