Like C++, in C language we cannot create a member function in the structure but with the help of pointer to function, we can provide the facility to user to store the address of the function.

A user can use this structure to store the address of a function using the function pointer as per the requirements and called this function whenever required in the program.

In my previous articles, I have already discussed the function pointer in c and its applications. Here I am discussing a simple example to how to use the pointer to function in structure.

How to use function pointer in structure

  • First, need to declare a function pointer as per requirements. In below example, I am creating two function pointers pfnMessage and pfnCalculator.

  • Create a structure which contains the above function pointers and float variable.

  • Now we will define the functions which perform the arithmetic operations like addition, subtraction, multiplication, and division.

  • In the last, we will define a function which will call one of the above define function as per the user choice.

Driver program to demonstrate the use of function pointer in structure

In below program user enter their choice to store the address of the function and call these function using the pointer to function.


When User choice: 1

When User choice: 2

When User choice: 3

When User choice: 4