Pointer to Array of functions in C 

Pointer to Array of Functions in C Language with Examples

In this article, I will discuss Pointer to Array of Functions in C Language with Examples. Please read our previous articles discussing Pointer-to-Pointer in C Language with Examples.

Pointer to Array of Functions in C:

In C, a pointer to an array of functions is essentially a pointer that points to an array, where each array element is a function pointer. This can be particularly useful for implementing things like lookup tables or dispatch tables, where you can call functions based on their index in the array.

Understanding Function Pointers

First, let’s understand a single function pointer. If you have a function like this:
int add(int a, int b) {
       return a + b;
}

A pointer to this function would be declared as:
int (*addPtr)(int, int) = add;

Pointer to an Array of Function Pointers

Now, if you want an array of such function pointers, you can do something like:
int (*funcArray[])(int, int) = {add, subtract, multiply, divide};
Assuming subtract, multiply, and divide are functions with the same signature as add.

Example: Using a Pointer to an Array of Functions

Let’s define a complete example with an array of functions and how to call these functions using pointers.

#include <stdio.h>

// Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);

int main() {
    // Array of function pointers
    int (*operations[])(int, int) = {add, subtract, multiply, divide};

    // Calling the functions using the array of function pointers
    int a = 10, b = 5;
    printf("Add: %d\n", operations[0](a, b));       // Add
    printf("Subtract: %d\n", operations[1](a, b));  // Subtract
    printf("Multiply: %d\n", operations[2](a, b));  // Multiply
    printf("Divide: %d\n", operations[3](a, b));    // Divide

    return 0;
}

// Function implementations
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 divide(int a, int b) {
    return (b != 0) ? (a / b) : 0;  // Guard against division by zero
}

In this example, we have an array named operations that stores pointers to four functions: add, subtract, multiply, and divide. Each of these functions takes two int parameters and returns an int. We can call these functions through the array using their indices.

Function tables example using Pointer to Array of functions in C

Let’s create an example in C where we use a function table with a pointer to an array of functions. This example will demonstrate a simple calculator that uses user input to perform different arithmetic operations like addition, subtraction, multiplication, and division.

#include <stdio.h>

// Function Prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);

int main() {
    // Function table (array of pointers to functions)
    int (*functionTable[])(int, int) = {add, subtract, multiply, divide};

    int choice, a, b;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    printf("Choose an operation:\n");
    printf("0: Add\n1: Subtract\n2: Multiply\n3: Divide\n");
    printf("Enter your choice (0-3): ");
    scanf("%d", &choice);

    // Check if the choice is within the valid range
    if (choice >= 0 && choice <= 3) {
        // Call the selected function from the function table
        int result = functionTable[choice](a, b);
        printf("Result: %d\n", result);
    } else {
        printf("Invalid choice!\n");
    }

    return 0;
}

// Function Implementations
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 divide(int a, int b) {
    if (b != 0) {
        return a / b;
    } else {
        printf("Error: Division by zero!\n");
        return 0;
    }
}
Explanation of the above Program:
  • Function Prototypes and Implementations: We define four functions (add, subtract, multiply, divide) with the same signature: they take two int arguments and return an int.
  • Function Table: An array of function pointers functionTable is created. This array holds pointers to the functions defined above.
  • User Input: The program asks users to input two numbers and select an arithmetic operation.
  • Function Execution: The corresponding function from the function table is called based on the user’s choice. An error message is displayed if the choice is outside the valid range.
  • Error Handling in Division: There’s a check in the divide function to prevent division by zero.
Usage

When you run this program, it will prompt you to input two numbers and then choose an operation (add, subtract, multiply, divide). Depending on your choice, it will execute the corresponding function and display the result.

Pointer to Array of Functions in C Language with Examples

This example effectively demonstrates how a function table using pointers to arrays of functions can be used to organize and execute a set of related operations in a clean and scalable way.

Callback Example using Pointer to Array of functions in C

Creating a callback system using a pointer to an array of functions in C is a great way to illustrate the flexibility and power of function pointers. In this example, we’ll set up a scenario where a function takes another function as an argument (a callback) and executes it. This is a fundamental concept in event-driven programming.

Example: Event Handler with Callback Functions: Imagine you’re writing a program that can respond to different “events” (like a button press or a timer expiry). We’ll simulate this by allowing the user to choose an event, and based on that choice, a corresponding callback function will be executed.

#include <stdio.h>

// Callback function prototypes
void onButtonPress();
void onTimerExpiry();
void onSensorTrigger();
void defaultAction();

// Array of pointers to callback functions
void (*eventHandlers[])(void) = {onButtonPress, onTimerExpiry, onSensorTrigger, defaultAction};

// Function that triggers events based on user input
void triggerEvent(int event) {
    if (event >= 0 && event < 3) {
        // Call the appropriate event handler
        (*eventHandlers[event])();
    } else {
        // Default action for invalid events
        (*eventHandlers[3])();
    }
}

int main() {
    int event;

    printf("Enter an event number (0 - Button Press, 1 - Timer Expiry, 2 - Sensor Trigger): ");
    scanf("%d", &event);

    // Trigger the event
    triggerEvent(event);

    return 0;
}

// Callback function implementations
void onButtonPress() {
    printf("Button was pressed.\n");
}

void onTimerExpiry() {
    printf("Timer expired.\n");
}

void onSensorTrigger() {
    printf("Sensor was triggered.\n");
}

void defaultAction() {
    printf("Invalid event. Executing default action.\n");
}
Explanation of the Above Program:
  • Callback Functions: onButtonPress, onTimerExpiry, onSensorTrigger, and defaultAction are functions that act as callbacks for different events.
  • Array of Function Pointers: eventHandlers is an array of pointers to these callback functions.
  • Triggering Events: The triggerEvent function takes an integer event, uses it to index into the eventHandlers array, and calls the corresponding function. If the index is out of range, it calls defaultAction.
  • User Interaction: The main function asks the user to input an event number and then triggers the corresponding event.
Usage

When you run this program, it prompts you to input an event number. It calls the corresponding event handler function depending on the number you enter. This example illustrates how a callback mechanism can be implemented using an array of function pointers, a common pattern in event-driven programming in C.

Key Points:
  • All functions in the array must have the same signature (i.e., the same return type and parameters) for this to work.
  • It’s crucial to ensure that the index used to access the array is within bounds to prevent undefined behavior.
  • This approach is useful for implementing strategies or command patterns, where the execution function can be chosen at runtime.

In the next article, I will discuss Pointer To Function in C Language. In this article, I try to explain Pointer to Array of Functions in C Language with Examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *