4

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.

assaf
  • 69
  • 2
  • 10
  • 1
    You don't need alloc space for your function - just allocate memory for your struct. – someuser Oct 17 '14 at 02:02
  • Who told you that you can't get the size of a void *pointer*? Have you tried, such as with `printf("%d", sizeof(void*));`? – HostileFork says dont trust SE Oct 17 '14 at 02:03
  • 1
    @HostileFork Concerning `"%d"`, you may way to check [this post](http://stackoverflow.com/questions/2524611/how-to-print-size-t-variable-portably) – chux - Reinstate Monica Oct 17 '14 at 03:37
  • @chux Worthwhile to point out. Though I did say "such as", and was more challenging the *I can't get the size of a void pointer* aspect vs. the infinity of questions that I would usually talk about *(such as, I think programming in raw C is archaic practice and printf is a bug magnet, but we're always speaking on some wavefront of understanding...)* – HostileFork says dont trust SE Oct 17 '14 at 03:54

3 Answers3

5

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.

user3473949
  • 205
  • 1
  • 8
3

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
  • 1
    "On 32bit pc, sizeof(a pointer) == 4." is not always true nor is the sizeof a function pointer necessarily the size of a data pointer. Testing in a certain platform/complier does show a value it could be but does not prove that is how it will be on others. – chux - Reinstate Monica Oct 17 '14 at 03:34
2

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.

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107