how to use void ** pointer correctly?

in His Steps picture in His Steps · Jan 27, 2012 · Viewed 47.6k times · Source

I am trying to use a double void pointer but I am a little bit confused about the usage. I have a struct that contains a void ** array.

struct Thing{
    void ** array;
};

struct Thing * c = malloc (sizeof(struct Thing));
c->array = malloc( 10 * sizeof(void *) );

So If I want to assign a different object to each pointer and try to retrieve the value

 // Option 1
 *(c->array + index) = (void *) some_object_ptr;

 // Option 2
 c->array[index] = (void *) some_object_ptr;

then, I have another function that gives (void *) item that points to each cell, not the some_object_ptr.

If I want to retrieve the value which pointed to by some_object_ptr,
should I do

 function return type is 'void *' and takes argument 'void *'
 // Option 3 
 return (void**) item

 // Option 4
 return *((void**)item)?

the weird thing is that when I used array the array subscript method I couldn't use option 4, only option 3; and when I used *(c->array + index) I could only use opt.4. and not opt.3. ..

Can anyone please tell me about this? If I am making any invalid assumptions, then could you please correct me?

Answer

Sylvain Defresne picture Sylvain Defresne · Jan 27, 2012

A void ** is just a pointer to a pointer to memory with an unspecified type. You can only dereference it once (since you can't dereference a void *). However, apart from that, it is basically like any other pointer type. If it helps you, think of it the same way as you would with int *.

So, in your specific situation, we have:

void** array;
int arrayLen = 10;
array = (void**)malloc(arrayLen * sizeof(void*));

some_type_t* some_object_ptr;    
// The following two assignment are equivalent since in C,
// array[index] <=> *(array + index)
array[index] = (void*)some_object_ptr;
*(array + index) = (void*)some_object_ptr;

Then array is a pointer to the whole array, while *array is a pointer to the first element, since it is equivalent to array[0].