diff options
author | Adam Bard <github@adambard.com> | 2013-07-04 09:41:45 -0700 |
---|---|---|
committer | Adam Bard <github@adambard.com> | 2013-07-04 09:41:45 -0700 |
commit | b59bbc949d773da612274ec1b176c25ac426f083 (patch) | |
tree | 3725bb520426024b6865939011a6411701acb257 /c.html.markdown | |
parent | 36f0eeac14a0f6207cc164472b51cb19aa326a59 (diff) | |
parent | fff3f61e2c64745eb4404ccaf582730e218043cf (diff) |
Merge pull request #102 from sergiokas/master
Adding small function pointers example in C
Diffstat (limited to 'c.html.markdown')
-rw-r--r-- | c.html.markdown | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/c.html.markdown b/c.html.markdown index 8786aa85..132f75dc 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -363,6 +363,36 @@ int area(rect r){ return r.width * r.height; } +/////////////////////////////////////// +// Function pointers +/////////////////////////////////////// +/* +At runtime, functions are located at known memory addresses. Function pointers are +much likely any other pointer (they just store a memory address), but can be used +to invoke functions directly, and to pass handlers (or callback functions) around. +However, definition syntax may be initially confusing. + +Example: use str_reverse from a pointer +*/ +void str_reverse_through_pointer(char * str_in) { + // Define a function pointer variable, named f. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at runtime) + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternative but equally valid syntax for calling it. +} + +/* +As long as function signatures match, you can assign any function to the same pointer. +Function pointers are usually typedef'd for simplicity and readability, as follows: +*/ + +typedef void (*my_fnp_type)(char *); + +// The used when declaring the actual pointer variable: +// ... +// my_fnp_type f; + ``` ## Further Reading |