Function pointer (Advanced C series Part 1)

Aniket Kumar
2 min readDec 8, 2024

--

  • Functions in C are compiled into binary data stored at specific memory addresses.
  • The function name represents the memory address of the code.
  • The syntax for defining a function in C is return_type function_name(parameter_list)

Example

//Example function

int add(int x, int y){
return x+y;}

//Declaring a function pointer
int (*f)(int, int) = sum;

// Call using the pointer:
int result = f(2, 4); // Equivalent to sum(2, 4)

Application of function pointer

  1. Enables dynamic behavior in functions.
    For example, Function filtering an array based on a predicate.
void print_if(int *arr, int size, int (*predicate)(int)) {
for (int i = 0; i < size; i++) {
if (predicate(arr[i])) {
printf("%d ", arr[i]);
}
}
}
int is_even(int x) {
return x % 2 == 0;
}
Usage
int numbers[] = {1, 2, 3, 4, 5};
print_if(numbers, 5, is_even); // Prints even numbers.

Here, the benefit of this type of programming is that, if lets say tommorow we want to do filtering based on odd number, we can create a new function for odd numbers and pass it to print_if.

This ensure that the original function print_if does not get modified, since we are not changing any code inside the function.

2) Standard Library Example: qsort:

  • The qsort function uses function pointers to sort arrays generically
void qsort(
void *base,
size_t num_elements,
size_t element_size,
int (*compare)(const void *, const void *)
);

int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}


//Casting to int*:

//Since a and b point to elements in an array of integers
// they are cast to int*:
// This converts the void* pointer to an int* pointer, allowing access to the integer values they point to.


//After casting, the pointers are dereferenced to get the actual integer values:

// *(int*)a
int numbers[] = {5, 2, 9, 1, 5, 6};
qsort(numbers, 6, sizeof(int), compare);

--

--

No responses yet