What Are Function Pointers?
Function pointers point to functions instead of data such as variables. They are variables that store the address of a function rather than a value.
In C, function pointers are used to achieve functionality such as callbacks, dynamic function invocation, and implementing function tables.
Below is a 3-step process of how function pointers are executed in a c program
1. Declaration
Function pointers are declared like any other pointer but with the function's return type and parameters specified.
returnType (*pointerName)(parameters);
2. Assigning Addresses
Function pointers are assigned the address of a function using the function's name.
returnType functionName(parameters)
{
// function body
}
pointerName = &functionName
// or pointerName = functionName
3. Calling the Function via Pointer
You can call the functioon using the function pointer like you would with the function itself.
(*pointerName)(arguments);
What Do Function Pointers Hold?
Function pointers hold the memory address of a function. They store the address from which the function code's starts in memory. This address points to the entry point of the function's machine code instructions.
Where Function Pointers Point in Memory
Function pointers point to the address in virtual memory where the machine code of the function is loaded during program execution. This address typically resides in the code segment of the program's memory layout.
When you use a function pointer, the processor fetches the machine instructions starting from the memory address stored in the function pointer and executes them accordingly.
Below is a simple example demonstrating how function pointers are executed:
#include <stdio.h>
// Function prototypes
void hello() {
printf("Hello, ");
}
void world() {
printf("world!\n");
}
int main() {
// Declare function pointer
void (*ptr)();
// Assign addresses of functions to the pointer
ptr = &hello;
// Call hello() function through the pointer
(*ptr)();
ptr = &world;
// Call world() function through the pointer
(*ptr)();
return 0;
}
Output:
Hello, world!
In the example above, ptr
is a function pointer that points to different functions (hello
and world
).
Depending on the assignment, it calls the appropriate function.
Top comments (2)
Functions via pointers can also be called without the
(*)
.And your
main()
function doesn't compile. (You should really compile all your examples.)Sure Paul!
First, I appreciate your feedback. I've corrected the code and it can now compile.
And yes, you're right, functions can also be called without the *. Read that after writing this article. Maybe I should edit to add more info on that.
Thanks