Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - Purpose of void*

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to compile you code with a serious ANSI C compiler, from C89 to C11, and you will get the same error:

Test.c(9): error #2168: Operands of '=' have incompatible types 'double *' and 'int *'.
Test.c(11): error #2168: Operands of '=' have incompatible types 'double *' and 'char *'.
Test.c(13): error #2168: Operands of '=' have incompatible types 'double *' and 'float *'.

I suppose that the online compiler is somewhat trimmed to accept any code also pre-ansi.
C is still a weak typed language, but such errors are not accepted by actual standard level.
C++ is more strong typed language (it needs it to work), so even the online compielr gives you the error.
The need of a universal pointer, void *, is absolutely required to act as a general pointer to be interchanged.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...