Lets say I have a struct called Student.
typedef struct student {
int age;
char name[10];
} Student;
And I have an array of pointers to Students.
Student *a[10];
I need to sort the array by the names of the students. So I wrote the comparison function:
int compare(const void *a, const void *b){
Student *temp1=*(Student **)a;
Student *temp2=*(Student **)b;
return strcmp(temp1->name, temp2->name);
}
Then I have the function to sort:
void SortArray(Student *a[], int len){
qsort(a, len, sizeof(Student *), *compare*);
printArray(a);
}
The last part of the qsort is what I don't get. I saw some posts where they wrote &compare, and some where they don't. Only when I used &compare it worked.
How do I know whether to use & or not?
compareonly, but I recommend you use&compareto make it more explicit for the readers of the code. - Some programmer dudecompare. - Amit&compareis explicit/readable in exactly the same way&array[0]is: confusing and gratuitously ugly to anyone who knows the language. Just usecompareorarray. Note that every time you call a function, as infunc(x), the namefuncis decaying to a pointer because the()operator (function call) requires a function pointer as its operand. - R.. GitHub STOP HELPING ICE