The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
A function pointer is nothing more than a variable that stores the address of a function. Once the address of a function is assigned to a pointer variable (function pointer), Then the respective function pointer can be used to access the function. Following simple program can clearly demonstrate the function pointer.
#include <stdio.h> void function(); // function declaration int main() { void (*ptr)(); // function pointer declaration ptr = &function; // function pointer initialization (*ptr)(); // Using function pointer return 0; } void function() // function definition { printf("Access me with my address"); }
In the above pointer to function program without any return type, we used void pointer (*ptr)() to hold the address of the starting point of the function, then this void pointer is used in line 7 to access the function.
#include <stdio.h> int function(); // function declaration int main() { int (*ptr)(); // function pointer declaration ptr = &function; // function pointer initialization printf("function pointer returns %d",(*ptr)()); // Using function pointer return 0; } int function() // function definition { int c = 4 + 4; return c; }
In the above pointer to function program with return type, we used integer pointer (*ptr)() instead of void pointer to hold the address of the starting point of the function, Then this integer pointer is used to invoke the function to return the summation value of 4 + 4.
#include <stdio.h> int function(); // function declaration int main() { int (*ptr)(); // function pointer declaration ptr = &function; // function pointer initialization printf("function pointer returns %d",(*ptr)(10)); // Using function pointer return 0; } int function(int i) // function definition { int c = i + 4; return c; }
The above program demonstrate that a function which is invoked by a pointer variable can be used to pass value to the function to perform some operation.
#include <stdio.h> int function(); // function declaration int main() { int (*ptr)(), i = 6, *iptr; // function pointer declaration iptr = &i; ptr = &function; // function pointer initialization printf("function pointer returns %d",(*ptr)(iptr)); // Using function pointer return 0; } int function(int *i) // function definition { int c = *i + 4; return c; }
The above program demonstrate that a function which is invoked by a pointer variable can be used to pass address of another variable to the function to perform some operation.
Function pointer just holds the address of staring point of a function but not the entire address in an array format.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019