BM Balmiki Mandal 10 Sep 2023 4 views 0 comments C Programming

Arrays of Pointers to Functions

Understanding Arrays of Pointers to Functions in C

An array of pointers to functions is a construct in C that allows you to store addresses of multiple functions in an array. This enables you to dynamically select and call a specific function at runtime based on the situation or conditions.

Here's an example to help you understand better:

c-programming
#include <stdio.h>

// Define two functions that we'll use in the array
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int main() {
    // Define an array of function pointers
    int (*func_ptr[3])(int, int) = {add, subtract, multiply};

    // Call the functions using the function pointers
    int result_add = func_ptr[0](4, 2);  // Calls add(4, 2)
    int result_subtract = func_ptr[1](4, 2);  // Calls subtract(4, 2)
    int result_multiply = func_ptr[2](4, 2);  // Calls multiply(4, 2)

    printf("Result of add: %d\n", result_add);
    printf("Result of subtract: %d\n", result_subtract);
    printf("Result of multiply: %d\n", result_multiply);

    return 0;
}

In this example, we have three functions (add, subtract, and multiply) that take two integer arguments and return an integer. We then declare an array of function pointers named func_ptr. Each element of this array is a pointer to a function that matches the signature int (*)(int, int) (a function that takes two integers and returns an integer).

We initialize the func_ptr array with the addresses of the three functions add, subtract, and multiply.

In the main function, we use these pointers to call the respective functions. func_ptr[0](4, 2) calls the add function, func_ptr[1](4, 2) calls the subtract function, and func_ptr[2](4, 2) calls the multiply function.

The output of this program will be:

Result of add: 6
Result of subtract: 2
Result of multiply: 8

 

This demonstrates how an array of pointers to functions can be used to select and execute functions dynamically based on the situation.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026