How to create a function pointer in C struct

C Function Pointer & Struct

In C programming, a struct is a user-defined data type that is used to group variables of different types under a single name.

In C programming, a function pointer is a pointer that points to a function.

Function pointer can be used to point to a function and stored the address of a function in struct.

Function pointer is used to pass a function as an argument to another function, create callback functions, or implement a dynamic function call mechanism.

Function pointer's return type and parameter type must match the function's return type and parameter type.

Create a Simple Function Pointer in a Struct

The following example demonstrates how to create a simple function pointer in a struct and use the function pointer to call a function:

Example of function pointer in a struct
Output of the above example
The sum of 10 and 20 is 30.

Explanation of code:

  • int AddNumber(int x, int y) { return x + y; }: This line defines a simple function named 'AddNumber' that takes two integer parameters (int x, int y) and returns their sum as interger type.
  • struct Math {.....};: This line defines a struct named 'Math'.
  • int (*AddNumber_ptr)(int, int);: This line defines a function pointer variable named 'AddNumber_ptr' (an asterisk '*' is used before the variable name) and the variable is placed inside parentheses. The pointer takes two integer parameter (int, int) and returns integer type. Here 'AddNumber_ptr' pointer's return type and parameter type match with 'AddNumber' function's return type and parameter type.
  • struct Math mathObj;: This creates an instance of the Math struct named 'mathObj'.
  • mathObj.AddNumber_ptr = AddNumber;: This initializes the function pointer 'AddNumber_ptr' assigning the address of the 'AddNumber' function to the pointer 'AddNumber_ptr' of the Math struct.
  • int result = mathObj.AddNumber_ptr(10, 20); This line calls the function 'AddNumber' using the function pointer 'AddNumber_ptr' and passing 10 and 20 as arguments and assigns the result of the function to the variable 'result'.
  • printf("The sum of 10 and 20 is %d.\n", result);: This line prints the result (sum of 10 and 20) in the console.

Live Code Playground

In the following C code editor, you can practice by creating more function pointers pointing to functions in a struct. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output