How to use function pointers inside a struct in C

4 Answers

0 votes
// Struct With One Function Pointer

#include <stdio.h>

struct Button {
    void (*onClick)();   // function pointer inside struct
};

void sayHello() {
    printf("Hello!\n");
}

int main() {
    struct Button b;
    b.onClick = sayHello;   // assign function

    b.onClick();            // call through struct
    
    return 0;
}


/*
run:

Hello!

*/

 



answered 19 hours ago by avibootz
0 votes
// Struct With Parameters in the Function Pointer

#include <stdio.h>

struct MathOps {
    int (*operation)(int, int);
};

int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }

int main() {
    struct MathOps m;

    m.operation = add;
    printf("Add: %d\n", m.operation(3, 4));

    m.operation = mul;
    printf("Mul: %d\n", m.operation(3, 4));

    return 0;
}


/*
run:

Add: 7
Mul: 12

*/

 



answered 19 hours ago by avibootz
0 votes
// Using typedef

#include <stdio.h>

typedef int (*op_t)(int, int);

typedef struct {
    op_t op;
} Calculator;

int sub(int a, int b) { return a - b; }

int main() {
    Calculator c;
    c.op = sub;

    printf("Result: %d\n", c.op(10, 3));
    
    return 0;
}



/*
run:

Result: 7

*/

 



answered 19 hours ago by avibootz
0 votes
// Function Pointers + Data Inside Struct (Callback)

#include <stdio.h>

typedef struct {
    int value;
    void (*callback)(int);
} Sensor;

void printValue(int v) {
    printf("Sensor value: %d\n", v);
}

int main() {
    Sensor s;
    s.value = 42;
    s.callback = printValue;

    s.callback(s.value);
    
    return 0;
}


/*
run:

Sensor value: 42

*/

 



answered 19 hours ago by avibootz

Related questions

...