LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Why do we need Function Pointers in C? (https://www.linuxquestions.org/questions/programming-9/why-do-we-need-function-pointers-in-c-906316/)

ArthurSittler 10-11-2011 04:12 AM

function pointers in C abstract data from algorithm
 
Function pointers in C are essential to abstract data type from algorithm. An example is the sort() function. It performs an in-place sort of an array. The best algorithm for sorting directory names or data points on a two-dimensional graph or any other sort of thing is the same algorithm. The sort algorithm needs some comparison function to decide if one object is "larger" than another of the same type. The comparison function for file names is very different from the comparison function for data points. Both functions can return a simple int result, however. The sort algorithm chooses two array elements for each comparison. The sort function passes the pointers to the two array elements to the compare function. Depending on the result of the comparison, the sort function may swap the two compared elements. Then the sort function goes on to choose the next two elements for comparison and so on until the array is sorted. The sort function library routine needs the address of the array of elements, the number of elements in the array, and a function pointer to the compare function.


All times are GMT -5. The time now is 01:27 PM.