I was trying to understand casting in C. I tried this code in IDEONE and got no errors at all:
#include <stdio.h>
int main(void) {
int i=1;
char c = 'c';
float f = 1.0;
double* p = &i;
printf("%d
",*(int*)p);
p = &c;
printf("%c
",*(char*)p);
p = &f;
printf("%f
",*(float*)p);
return 0;
}
But when compiled on C++ compiler here I got these errors:
prog.cpp:9:15: error: cannot convert 'int*' to 'double*' in initialization
double* p = &i;
^
prog.cpp:11:4: error: cannot convert 'char*' to 'double*' in assignment
p = &c;
^
prog.cpp:13:4: error: cannot convert 'float*' to 'double*' in assignment
p = &f;
^
and this is compatible with what I know so far; that is, I can't assign (in C++) incompatible types to any pointer, only to void *
, like I did here:
#include <stdio.h>
int main(void) {
int i=1;
char c = 'c';
float f = 1.0;
void* p = &i;
printf("%d
",*(int*)p);
p = &c;
printf("%c
",*(char*)p);
p = &f;
printf("%f
",*(float*)p);
return 0;
}
Now, if this code runs perfectly well in C, why do we need a void
pointer? I can use any kind of pointer I want and then cast it when needed. I read that void
pointer helps in making a code generic but that could be accomplished if we would treat char *
as the default pointer, wouldn't it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…