Search code examples
cpointersstructure

Function Pointer present inside a structure in C


I am working on a problem of running a function through a function pointer, which is a variable of a structure. I tried making a small code but I am not able to build it. The error I am getting is as below: enter image description here Please review the code below. The first statement in the main function is the cause of the error. I am new to C.Thank you for your kind help.

#include <stdio.h>
#include <stdlib.h>
#include<stdint.h>

typedef int16_t (*reset_start_f)(void);        //typedef used for function Pointer

int ThermMgrSvc_Reset(void)
{
    int retVal;
    retVal=5;
    return retVal;
}



typedef struct
{

    reset_start_f reset;   // function pointer

}module_function_t;





static const module_function_t MODULE_TABLE[]=
{
    {(reset_start_f)ThermMgrSvc_Reset},
};


int main()
{
    int x2= MODULE_TABLE[0].(*reset)();           // This statement causing Error
    printf("x2= %d\n",x2);


    return 0;
}

Solution

  • This syntax is invalid:

    int x2= MODULE_TABLE[0].(*reset)();
    

    Because the structure access operator . must be followed immediately by the name of the field. The dereferencing operator needs to be before the whole subexpression:

    int x2= (*MODULE_TABLE[0].reset)();
    

    Or, since function pointers are dereferenced implicitly when called, you can remove the * entirely:

    int x2= MODULE_TABLE[0].reset();