I have a function which creates an array of pointers. The function which allocates the memory returns the new memory pointer through a parameter passed to the function. The simplest code which can reproduce the problem is as follows:
void foo (void** new_mem, size_t bytes)
{
*new_mem = malloc(bytes);
}
int main (void)
{
int** ptr_arr; // Want to create an array of pointers
foo(&ptr_arr, sizeof(int*)*100); // Create an array size of 100
// compiler emits warning:
// 'void **' differs in levels of indirection from 'int ***'
return 0;
}
I could cast the first parameter passed to foo like so: ‘(void**)&ptr_arr’ to get rid of the warning, however, I’m wondering: Is there a more appropriate solution?
Although there’s a guaranteed conversion from
int *tovoid *, there’s no such guarantee for converting fromint **tovoid **. To think about why this might be, consider that anint *might actually be smaller than avoid *. As a result, using avoid **pointer to walk over an array ofint *s will walk the wrong stride and get the wrong data. Furthermore, there’s no guarantee thatint *will use the same representation asvoid *, only that there is a way to convert between them.In practice, I don’t know of any machines where this will fail. But it’s not guaranteed by the standard.
EDIT: eek, and what everyone says about passing an
int ***. But even if you pass anint **, the above still applies.EDIT2: the comp.lang.c FAQ has an excellent discussion about this.