#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的同时完成了初始化吗?
这是有效的C,但无效的C ++。(C ++并不隐式地从void*:进行强制转换,这就是为什么您倾向于malloc在C ++程序员编写的C代码中看到很多不必要的强制转换!)
在MSVC上,将文件重命名为具有扩展名.c,一切都会好起来:MSVC对该扩展名调用C编译器。