summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorsergiokas <dev@sergiokas.com>2013-07-03 23:57:37 -0300
committersergiokas <dev@sergiokas.com>2013-07-03 23:57:37 -0300
commit3308c9c015e130b4e813f998898852d9fc2d7e05 (patch)
tree5f8e10120ac1e00a4659893093e0d5b944b14c67
parent69e191458a6377e2b3e7bdb2126a046cc4ec7967 (diff)
Adding small function pointers example
-rw-r--r--c.html.markdown24
1 files changed, 24 insertions, 0 deletions
diff --git a/c.html.markdown b/c.html.markdown
index 69bf099e..fba587fc 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -323,6 +323,30 @@ str_reverse(c);
printf("%s\n", c); // => ".tset a si sihT"
*/
+/*
+Functions are located in known memory addresses, so they can be called
+through function pointers. 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 alternate but equally valid syntax for calling it.
+}
+
+/*
+As long as function signatures match, you can assign any function to the same pointer.
+Useful for passing handlers (or callback functions) around.
+Function pointers are usually typedef'd for simplicity and readability, as follows:
+
+typedef void (*my_fnp_type)(char *);
+...
+my_fnp_type f;
+*/
+
///////////////////////////////////////
// User-defined types and structs
///////////////////////////////////////