{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

49_pdfsam_cs2022

# 49_pdfsam_cs2022 - Uses of function pointers Writing...

This preview shows pages 1–6. Sign up to view the full content.

Uses of function pointers Writing generic code A function can take a function as a parameter Example: a generic function to compute integrals double compute_integral(double a, double b, double (*f)(double)) { /* lots of code */ } double x_squared(double x) { return x * x; } double x_cubed(double x) { return x * x * x; } int main() { compute_integral(0, 1, x_squared); compute_integral(5, 9, x_cubed); }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Function pointer example #include <stdio.h> void change_array( int *a, int size, int (*f)(int)) { int j; for( j=0; j < size; j++) a[j] = f(a[j]); } int add_one(int x) { return x + 1; } int square(int x) { return x * x; } int main() { int a[5] = { 0, 1, 2, 3, 4 }; change_array(a, 5, add_one); // increment every element change_array(a, 5, square); // square every element return 0; }
Other examples qsort(), heapsort(), mergesort() are standard library functions for generic sorting defined in stdlib.h They take a comparison function as a parameter They can sort any type of array, as long as an appropriate comparison function is given Also available: lsearch() : linear search bsearch() : binary search through a sorted array

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern