简体   繁体   中英

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.

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.

You don't need to malloc space.

On 32bit pc, sizeof(a pointer) == 4.

You can test if

sizeof(struct example) == 8
sizeof(int) == 4

You don't need to allocate memory for the function you're going to point to. It already exists and occupies space; it is allocated when you compile your program and you do not manage it explicitly. You simply take its address and assign it to the pointer.

Regarding memory for the pointer itself, it will be provisioned when you allocate memory for the structure it is a member of. When you compute sizeof struct example , the size of both the int and the function pointer are considered, as well as any padding bits that were added for proper alignment. Passing such size to malloc will ensure you have enough memory for the entire structure, including the pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM