指针-'正在初始化':无法从'void'转换为'int'

Ahm*_*Zul 2 c pointers void

#include <stdio.h>
int main()
{
    int a = 10;
    void *p = &a;
    int *ptr = p; // the error occurs here (cannot convert from 'void' to 'int')
    printf("%u",*ptr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

该错误如上所述。为什么会发生错误?是因为在将指针声明为void的同时完成了初始化吗?

Bat*_*eba 5

这是有效的C,但无效的C ++。(C ++并不隐式地从void*:进行强制转换,这就是为什么您倾向于malloc在C ++程序员编写的C代码中看到很多不必要的强制转换!)

在MSVC上,将文件重命名为具有扩展名.c,一切都会好起来:MSVC对该扩展名调用C编译器。