Concept

How are generic getMax() functions used with integers and structures?

ComputerScienceOne / Function Pointers

"Suppose we have an array of integers and the cmpInt() comparator function above. We can use our getMax() function as follows.\n\nint arr[] = {8, 2, 9, 10, 4, 2, 2, 5, 6, 7};\n\nint maxIndex = getMax(arr, 10, sizeof(int), cmpInt);\n\nprintf(\"maximum value: %d\n\n\", arr[maxIndex]);\n\nIn this example, the getMax() function would return the index 3 and print the maximum value stored there, 10. The getMax() function returns the index corresponding to the “maximum” element according to the comparator used. If instead we had used cmpIntDesc() the “maximum” element would have been the least element, (2 in the example above) because it would have been the element ordered “last” by the descending comparator.\n\nConsider another example with our Student structure.\n\nint n = 10;\n\nStudent *roster = (Student *) malloc(sizeof(Student) * n);\n\n...\n\nint maxIndex = getMax(roster, n, sizeof(Student), studentByNameCmp);\n\nSince studentByNameCmp() orders by lexicographic ordering, a student with the last name “Zadora” would have been “larger” than someone with a last name “Anderson.” Thus the code above will return an index corresponding to the last student in lexicographic ordering of their name. Similarly, if we had used the studentGpaCmp() comparator instead, getMax() would have returned an index for the student with the lowest GPA as this comparator ordered highest to lowest.\n\nAnother variation on this function would be to return a pointer to the maximum element rather than an index. The same logic would have applied, but the return type would be a void * pointer and the return statement would return the memory address of the maximum element instead. To avoid warnings, in the final return statement we cast arr as a void pointer (instead of a const void pointer) to make the return value compatible with the return type.\n\nvoid * getMax(const void *arr, int n, size_t size,\n\nint(*cmp)(const void *, const void *)) {\n\nint i, maxIndex = 0;\n\nfor(i=1; i<n; i++) {\n\nif(cmp(arr + maxIndex * size, arr + i * size) < 0) {\n\n//we've found something larger, update the max_index:\n\nmaxIndex = i;\n\n}\n\n}\n\nreturn (void *)arr + maxIndex * size;\n\n}"

Related Ideas

How are generic getMax() functions used with integers and structures? | ComputerScienceOne | Bifalgorithm | Bifalgorithm