c - Purpose of void* -
i trying understand casting in c. tried this code in ideone , got no errors @ all:
#include <stdio.h> int main(void) { int i=1; char c = 'c'; float f = 1.0; double* p = &i; printf("%d\n",*(int*)p); p = &c; printf("%c\n",*(char*)p); p = &f; printf("%f\n",*(float*)p); return 0; }
but when compiled on c++ compiler here got these errors:
prog.cpp:9:15: error: cannot convert 'int*' 'double*' in initialization double* p = &i; ^ prog.cpp:11:4: error: cannot convert 'char*' 'double*' in assignment p = &c; ^ prog.cpp:13:4: error: cannot convert 'float*' 'double*' in assignment p = &f; ^
and compatible know far; is, can't assign (in c++) incompatible types pointer, void *
, did here:
#include <stdio.h> int main(void) { int i=1; char c = 'c'; float f = 1.0; void* p = &i; printf("%d\n",*(int*)p); p = &c; printf("%c\n",*(char*)p); p = &f; printf("%f\n",*(float*)p); return 0; }
now, if code runs in c, why need void
pointer? can use kind of pointer want , cast when needed. read void
pointer helps in making code generic accomplished if treat char *
default pointer, wouldn't it?
try compile code serious ansi c compiler, c89 c11, , same error:
test.c(9): error #2168: operands of '=' have incompatible types 'double *' , 'int *'. test.c(11): error #2168: operands of '=' have incompatible types 'double *' , 'char *'. test.c(13): error #2168: operands of '=' have incompatible types 'double *' , 'float *'.
i suppose online compiler trimmed accept code pre-ansi.
c still weak typed language, such errors not accepted actual standard level.
c++ more strong typed language (it needs work), online compielr gives error.
need of universal pointer, void *
, absolutely required act general pointer interchanged.
Comments
Post a Comment