0

I have the following line of code in my C program.

sprintf(cmd, "test mergesort %n %x %x %?", A, n, x, my_cmp);

my_cmp is of type Compare_fn and I need to know how to pass it into this function. This line is used to help execute a command needed for testing purposes.

If anyone knows how to pass a variable of type Compare_fn into this function, it would be really helpful.

I'm not trying to print anything with my_cmp at all. I have a function that has Compare_fn variable as a parameter and am simply executing the function in the shell.

user1261445
  • 291
  • 1
  • 6
  • 15
  • What are you actually trying to do? Print the results of `my_cmp(n, x)` ? – John3136 Aug 15 '12 at 00:52
  • What is `Compare_fn`? Some type of function pointer? If you want to get the name of the function pointed too by a function pointer, there's no easy way to do it. See [this answer](http://stackoverflow.com/questions/351134/how-to-get-functions-name-from-functions-pointer-in-c) for some more info. – Michael Mior Aug 15 '12 at 01:18
  • What is compare_fn defined as? – Scooter Aug 15 '12 at 02:24

1 Answers1

2

ISO C does not define a conversion from function pointer types to void *, but almost all implementations do define such a conversion (and POSIX requires it to be defined), which you can use to convert the function pointer to void * and print it with %p. If you don't want to rely on this, you can use the fact that all types in C are required to have a representation as an overlaid array of unsigned char:

Compare_fn fp;
unsigned char rep[sizeof fp];
memcpy(rep, &fp, sizeof rep);
for (i=0; i<sizeof rep; i++) printf("%.2x", rep[i]);

Obviously you could store the hex output to a string instead of stdout if you prefer, using snprintf or your own byte-to-hex code.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711