October 27, 2024
Chicago 12, Melborne City, USA
C#

How to pass a function pointer as a parameter of another function?


I’m currently working on a project about sorting void arrays (we don’t know the variable types until runtime). Since it can be string, float or int, I’ve created a function that creates the array with a function pointer parameter which is then assigned to a specific compare function based on the variable type.

void** get_field_array(p_data* data_array, size_t field, size_t n_items, size_t* size, int (*compar)(const void*, const void*));
// Content of get_field_array function:
switch(field) {
case 1:
compar = &compar_string;
// [...]

case 2:
compar = &compar_int;
// [...]

case 3:
compar = &compar_float;
// [...]
}

The function that calls get_field_array() creates a int (compare)(const void, const void*) variable that stores the correct compare function to use.
My question is: how do I pass the *compare variable in get_field_array in order to keep the value of it outside of the function? Do I need to pass it as (**compare)? Thanks in advance, I hope I explained the problem clearly.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video