2

In C what's the function pointer (void*) doing in:

    int (*fn) (void*)

If the parameter is nothing then it should be:

    int (*fn) ()

My understanding is void* is chunk of memory. void* mem means mem pointing to a chunk of memory. But what's (void*) without a name?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
lilzz
  • 5,243
  • 14
  • 59
  • 87
  • 3
    "If the parameter is nothing then it should be" Just note: In C language, `void foo()` doesn't mean a function with no parameters; unlike,it's means a function with undefined number of arguments. So,a call like this is valid totally: `foo(1,"abc",2.3)`. If you want to specific a function with 0 argument,you need to use `void` between `()` like this: `void foo(void)`. – Jack May 26 '13 at 01:53

4 Answers4

6

That function pointer declaration does not require you to give the void* a name. It only requires a type to define the argument list.

This is similar to how:

void my_function(int x);

is just as valid as

void my_function(int);
user123
  • 8,970
  • 2
  • 31
  • 52
  • 1
    Further, the parameter name used in the function prototype does not have to match the parameter name used in the function definition. You could have `extern char *strcpy(char *target, const char *source);` and write `char *strcpy(char *dst, const char *src) { while ((*dst++ = *src++) != '\0') ; }` as the implementation. – Jonathan Leffler May 26 '13 at 02:30
4

void * is an anonymous pointer. It specifies a pointer parameter without indicating the specific data type being pointed to.

lurker
  • 56,987
  • 9
  • 69
  • 103
2

An unnamed parameter is not the same thing as no parameters. The declaration:

int (*fn)(void*);

merely states that fn is a function pointer that takes a void* argument. The parameter name is inconsequential (and is only meaningful in the function implementation where it's the name of the local variable).

(Although it the parameter name is not necessary in function declarations, it is nevertheless useful to people reading the code to identify what the parameter is.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
1

It means that fn is "any function that takes a block of memory as a parameter, and returns an int"

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58