Engine
Engine

Reputation: 5432

how can I use void** function(void**)

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 !

Upvotes: 3

Views: 327

Answers (3)

Kurt Pattyn
Kurt Pattyn

Reputation: 2798

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);

Upvotes: 1

Jacob Pollack
Jacob Pollack

Reputation: 3761

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;
}

Upvotes: 7

Tony The Lion
Tony The Lion

Reputation: 63310

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);

Upvotes: 4

Related Questions