Nov 6, 2024
#include<stdio.h>
void fun(int a) { printf("Value of a is %d\n", a); }
int main() {
void (*fun_ptr)(int) = &fun;
(*fun_ptr)(10);
return 0;
}
Output: Value of a is 10Function pointers point to code, unlike normal pointers that point to data.
No memory allocation/deallocation is needed for function pointers.
Function names can be used to get their address directly.
& and * operators:
void (*fun_ptr)(int) = fun;
fun_ptr(10);
Arrays of function pointers can be created:
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
Function pointers can replace switch-case constructs.
Function pointers can be passed as arguments and returned from functions.
int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); }
qsort(arr, n, sizeof(int), compare);
int search(void *arr, int arr_size, int ele_size, void *x, bool compare(const void*, const void*))