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

call a function inside struct but struct inside a void*

Can I first allocate a struct (with a function inside) to a void* and trigger the function inside them.

struct func {
    void (*fp)(); // this is a function
};

struct thread{
    void *stack; // I'm gonna use this to store 'struct func' above
};

void assign(struct thread *t,void *f()){
    struct func *task = (struct func *)malloc(sizeof(struct func));
    task->fp = f;
    t->stack = task;
    
    // question: now I want to call the function inside func and deeper inside void*
    // I mean: trigger the function fp()
    t->stack->fp(); // error here

}

>Solution :

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

The stack member has type void * and therefore can’t be dereferenced as is.

You would first need to cast it to the proper pointer type (or assign to a pointer of that type) before dereferencing.

((struct func *)t->stack)->fp();
// or
struct func *f = t->stack;
f->fp();
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