Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to malloc space for function pointers in a struct in C?

For example, I have to create a struct in a function with the parameters: a function pointer with the format: void (*func)(void *) and an int id.

The struct to create is the following:

typedef struct example {
    int id;
    void (*func)(void *);
} Example;

Now my question is when I malloc space for the whole struct, do I also malloc space for the void function pointer because it is a pointer? If so, how, since I can't get the size of a void pointer? Thanks.

like image 635
assaf Avatar asked Dec 25 '22 03:12

assaf


1 Answers

When you malloc space for a struct, sizeof(your_struct) gets you the size of the entire struct. You don't need to individually allocate space for each element. After mallocing, you can set the function pointer like any other field of the struct.

like image 147
user3473949 Avatar answered Dec 27 '22 15:12

user3473949