Function Pointer Function Pointer
Total Page:16
File Type:pdf, Size:1020Kb
Function A group of statements Starts from a certain address Function Pointer Function name itself is a pointer pointing to the start address of the function Stanley Yao A function name contains many information Computer Science Department Point to the starting address of then function University of Arizona Function pointer base type Parameter type list Return value type Csc352-Summer03, Stanley Yao 2 Function, Variable and Pointer Function Pointer int (*func)(int foo); int (*p2)(void); func: a function pointer int *p1; “func” points to a function that takes an int …… as parameter and returns int i (of type int) The base type of “func” is a function that …… takes an int and returns an int int foo(void) { <statements> Compare: int *func(int foo); } Csc352-Summer03, Stanley Yao 3 Csc352-Summer03, Stanley Yao 4 Using Function Pointers qsort void foo (void) { ptr void qsort(void *base, size_t nel, size_t width, printf(“hello\n”); int (*compar) (void *, void *)); } qsort() routine in the C library void main (void) { void (*ptr)(void); The data items to be sorted can be of any type and ptr = foo; size. How does qsort compare them during the (*ptr)(); // foo(); sorting? } foo() base: address of the arrary of elements to be sorted ptr: a function pointer nel: number of elements in the array *ptr: the function to which “ptr” points to width: size (in bytes) of each element (*ptr)(): a call to the function compar: pointer to the compare function Csc352-Summer03, Stanley Yao 5 Csc352-Summer03, Stanley Yao 6 1 Object Acknowledgement struct __db { char *filename; John H. Hartman, Classnotes for Csc352- int type; Spring03, CS Dept., University of Arizona, int (*get) (struct __db *dbp, void *key, void *data); int (*put) (struct __db *dbp, void *key, void *data); 2003 …… }; Brian W. Kernighan, Dennis M. Ritchie, The C Programming Language (2nd Ed.), Prentice Wrap data and functions in a structure Hall, 1988 Need to initialize the function pointers when initializing the object struct __db dbp; dbp.get = my_get_func; Csc352-Summer03, Stanley Yao 7 Csc352-Summer03, Stanley Yao 8 2.