Compilation warning for void ** and void *

I have a question regarding void* and void** , and I know this is kind of an old question and has been asked (somewhat) earlier in stackoverflow. So the question is:

When I compile this code with gcc 4.4.3 under ubuntu 10.10, I get the following warning:

 zz.c: In function 'main': zz.c:21: warning: passing argument 1 of 'bar' from incompatible pointer type zz.c:9: note: expected 'void **' but argument is of type 'float **' 

why it is ok to pass the variable x as an argument to foo (), but it fails to pass the variable y as an argument to bar (). I can fix this by explicitly translating both variables into void* and void** , as expected.

 void foo (void* a){ } void bar(void **a){ *a = (float *) malloc(100*sizeof(float)); } int main (){ float *x = (float*) malloc(100*sizeof(float)); foo(x); free(x); float *y; bar(&y); free(y); return 0; } 
+4
source share
3 answers

void *a means that a points to an object of an unknown type. However, a by itself is not an unknown type, since a is known to be of type void* . Only the object pointed to by a has an unknown type.

void **a means that a points to an object of type void* . The object pointed to by *a has an unknown type, but the object *a is a pointer of type void* .

&y is a pointer to an object of type float* . &y not a pointer to an object of type void* .

+10
source

The C ++ standard allows any pointer to be implicitly converted to void* . But void** is not the same as void* ; it is a pointer to void* . Consequently, it falls under the rules for regular pointer conversions (i.e., it is forbidden without a throw, with some exceptions).

+5
source

Adding to the information in other answers, void* acts as a general type of pointer in C. There is general information about this: any pointer (except the type of a pointer to a function) can be converted to void * and vice versa without losing information, and the pointer expression (again , except for a pointer to a function) can be implicitly converted to void* . (C ++ has slightly different rules.)

You might think that void** is a generic type of pointer to pointer, but it is not. This is a pointer to a specific type, namely void* . In fact, C does not have a generic pointer type to a pointer. But it has a generic pointer type, so any code that tries to use void** as a generic type of pointer to a pointer might just use void* instead.

+3
source

All Articles