Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a function pointer in a structure?

I have declared typedef void (*DoRunTimeChecks)();

How do I store that as a field in a struct? How do I assign it? How do I call the fn()?

like image 783
Mawg says reinstate Monica Avatar asked Mar 25 '12 05:03

Mawg says reinstate Monica


People also ask

Can you have a function pointer in a struct?

Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.

How do you store a pointer in a structure?

Whenever you have pointers inside a structure, you have to use malloc() or calloc() , otherwise they will be stored wherever string constants are stored. Use a pointer to store the address, and use a memory allocation function to allocate just the amount of memory needed for a string.

Can structure store functions?

No, structure supports only a pointer to a function.


1 Answers

Just put it in like you would any other field:

struct example {
   int x;
   DoRunTimeChecks y;
};

void Function(void)
{
}

struct example anExample = { 12, Function };

To assign to the field:

anExample.y = Function;

To call the function:

anExample.y();
like image 151
Carl Norum Avatar answered Sep 21 '22 13:09

Carl Norum