cstructfunction-pointers

Using a function pointer inside a struct


I am trying to use a struct as a function container, but I am unable to do so. Here is my code for the struct aliased as methods

typedef struct {
        void (*addAtHead)(LinkedList*,int);
        void (*addAtTail)(LinkedList*,int);
        void (*remFromHead)(LinkedList*);
        void (*remFromTail)(LinkedList*);
}methods;

And here I am pointing the methods's pointers to corresponding functions

methods LinkedListF;
LinkedListF.addAtHead = addAtH;
LinkedListF.addAtTail = addAtT;
LinkedListF.remFromHead = remFromH;
LinkedListF.remFromTail = remFromT;

It was expected that the LinkedListF.addAtHead(LinkedList *l,int value) function call will call addAtH, but during compilation, it gives

LinkedList.c:43:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
   43 | LinkedListF.addAtHead = addAtH;
....and more errors

I have verified that there are no missing semicolons or other mistakes, also if I try with the following code, it correctly compiles

methods LinkedListF = {addAtH,addAtT,remFromH,remFromT};

Can somebody please explain where I am doing wrong?


Solution

  • You have the following outside of a function:

    methods LinkedListF;
    LinkedListF.addAtHead = addAtH;
    LinkedListF.addAtTail = addAtT;
    LinkedListF.remFromHead = remFromH;
    LinkedListF.remFromTail = remFromT;
    

    Only declarations are allowed outside of functions. The last four of those lines are not declarations but expression statements which can only be found inside functions.

    This works inside of a function.

    The desired effect can also be obtained by using a declaration with an initializer.

    methods LinkedListF = { addAtH, addAtT, remFromH, remFromT };
    
    methods LinkedListF = {
       .addAtHead   = addAtH,
       .addAtTail   = addAtT,
       .remFromHead = remFromH,
       .remFromTail = remFromT,
    };
    

    These work inside or outside of a function.

    Both the failing approach and the working approaches use =, but = inside a declaration denotes an initializer instead of an assignment.