When would you use a pointer to a function?
Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, “Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me.” This is known as a “callback.” It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application. As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. (For more on sorting, see Chapter III, “Sorting and Searching Data.”) qsort() takes four arguments, Ø a pointer to the beginning of the array, Ø the number of elements in the array, Ø the size of each array element, and Ø a comparison function, and returns an int.
-
Interview Candidate
- Mar 6th, 2005
- 1
- 2496
Showing Answers 1 - 1 of 1 Answers
Related Answered Questions
Related Open Questions
When would you use a pointer to a function?
Related Answered Questions
Related Open Questions