notes53 - CS251 Class Notes -Volunteer to take class notes...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS251 Class Notes -Volunteer to take class notes for a week. -Write them in HTML -Pictures in GIF/JPEG -Mail them to grr@cs.purdue.edu -2% extra credit Lab 3 Pointers to Functions -They represent the address of a piece of code. -Pointers to functions are used to implement polymorphism in C. -Polymorphism of some piece of code for arguments that have different types. Example: Sorting function of array no matter the type of elements. Example: Array Mapper - A procedure that executes a function for every entry in the array. typedef void(* FuncPtr)(int a); void intArrayMapper(int *a, int n, FuncPtr func) { //Call "func" for every entry in array. for(int i=0; i<n; i++) { (*func)(a[i]); } } int s; void sumInt (int v) { //Accumulates the sum of argument a into s. s += v;} } void printInt(int v) { printf("%d\n", v); } int a[] = {3,4,7,8}; main() { //Print values in array. int n = sizeof(a) / sizeof(int) ; intArrayMapper(a, n, printInt); //Print sum. s = 0;
Background image of page 1

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

View Full DocumentRight Arrow Icon
intArrayMapper(a, n, sumInt); printf("sum=%d", s); } -The previous example only works for integer arrays. -A generic array mapper can work with arrays of any type. typedef void (*GenFuncPtr)(void *); void genericArrayMapper(void *a, int n, int elementSize, GenFuncPtr func) { for(int i=0; i<n; i++) { void *p_ith = (void*((char*)a + i * elementSize)); (*func)(p_ith); } } int s; void genSumInt(void *pv) { int *v = (int *)pv; s += *v; } void genPrintInt(void *pv)
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 5

notes53 - CS251 Class Notes -Volunteer to take class notes...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online