Purpose of void*

六月ゝ 毕业季﹏ 提交于 2019-12-13 11:29:02

问题


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\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 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\n",*(int*)p);
    p = &c;
    printf("%c\n",*(char*)p);
    p = &f;
    printf("%f\n",*(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?


回答1:


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.



来源:https://stackoverflow.com/questions/34830416/purpose-of-void

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!