Function Pointer Function Pointer

Function Pointer Function Pointer

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.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    2 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us