Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add functions to members of struct in c

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading