3

I was reading a program and I found this function:

void** function(void**) 

My question is what kind of parameter can I give and what should my return value be ?

*UPDATE!!! *

I can read it and I know it's can be a pointer of a pointer on any type the question is how to use it ?? ( I've just edited the title ) thanks in advance !

4

3 回答 3

7

The function declaration:

void **functionName( void**);

... is read as: "functionName is a function that is passed a double void pointer and returns a double void pointer". It is passed a double void pointer and returns a double void pointer.

It is extremely common to see void pointers in generic ADTs, compare functions, destroy functions, etc. (left this detail out but it's important -- mentioned in OPs comments).

Example (non-sensical function):

Consider this as your array. Say you wanted to mutate the first element to be the string "Hai" as oppose to "Hello" (it is too classy).

char *arr_of_str[] = { "Hello", "Hi", "Hey", "Howdy" };

... then your function we be as follows:

void **functionName( void** ptr ) {
  char **ptr_char = ptr;

  ( *ptr_char )[ 0 ] = "Hai";

  return ptr;
}
于 2013-08-14T09:28:53.773 回答
4

It is a function that takes a pointer to pointer to void and returns a pointer to pointer to void.

You could use it like this:

int something = 5;
void* somepointer = &something;

functionName(&somepointer);
于 2013-08-14T09:26:08.363 回答
1

A void * can refer to an address of any type. You can read it as: 'a pointer to something in memory'. So this means, it can point to an integer, a string, an object, ... everything. Some examples:

void *anyObject;
int a = 1;
float b = 2;
char *c = "somestring";

function aFunction(int a)
{
   ...
}

anyObject = &a;
anyObject = &b;
anyObject = &c;
anyObject = &aFunction;

These are all valid assignments.

To come back to your question: a void ** is a pointer to a pointer to void; in proper English: it points to a location in memory where the value of void * is stored. Continuing from the above example:

void **p;
p = &anyObject;

In general, void * are dangerous, because they are not type safe. In order to use them, you MUST cast them to a known type. And the compiler will not complain if you cast it to something illegal.

Okay, how do you use it? Well, that is difficult to answer because we cannot derive from the declaration what types are expected. Also, it is possible that this functions allocates memory itself inside the function and returns that within the parameter. But, the general principle is: take the address (&) of 'a pointer to something', and pass that to the function.

int a = 0;
int *pa = &a;
functionName(&pa);
于 2013-08-14T09:46:41.597 回答