0

I need to include a function inside member of a struct in c. How can i do this?

I researched a bit, but didn't find anything. I am kind of new to c and dont know much of its uses.

#include<stdio.h>

//so i have a struct like this
typedef struct{
    void (*func)(void);
}test;

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

//as far as i have searched -> i have come up to this

int main()
{
    test a;
    *a.func = *testfunction();
    //this doesn't work
    a.func();
}

I think that this should be possible, but I don't know how to do it. Any help is appreciated.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Pear
  • 351
  • 2
  • 12

1 Answers1

3

void *func; is not a valid pointer to function, comments in code:

#include<stdio.h>

typedef struct{
    void (*func)(void); // Don't forget to include the arguments
}test;

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

int main()
{
    test a;
    a.func = testfunction; // Without parentheses / Without dereferencing
    a.func();
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94