I have a question regarding void*
and void**
and I know this is sort of an old question and has been asked (somewhat) before in stackoverflow. So the question is the following:
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 is it that its ok to pass variable x as an argument of foo() but its not ok to pass variable y as an argument of bar(). I can fix this by explicitly casting 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;
}
void *a
means that a
points to an object of unknown type. However, a
itself is not an unknown type because a
is known to have type void*
. Only the object that a
points to has an unknown type.
void **a
means that a
points to an object of type void*
. The object that *a
points to has an unknown type, but the object *a
itself is a pointer with type void*
.
&y
is a pointer to an object of type float*
. &y
is not a pointer to an object of type void*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With