c ++-malloc转换错误 [英] c++ - malloc casting error
本文介绍了c ++-malloc转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Everyones suggesting not to cast while allocating a pointer here, do I cast result of malloc
但是我下面的未广播代码在VS-2013中产生了编译器错误.为什么!
But my below non-casted code produce compiler error in VS-2013. Why!
#include <stdio.h>
#include <malloc.h>
int main(){
int *ptr = malloc(sizeof(int) * 100); // compiler error
return 0;
}
编译器错误是
1 IntelliSense:类型"void *"的值不能用于初始化 类型为"int *"的实体
1 IntelliSense: a value of type "void *" cannot be used to initialize an entity of type "int *"
推荐答案
另一个问题中的建议仅适用于C
.
The advice in the other question is strictly for C
only.
在C++
中,您需要进行强制转换,因为C++
不允许将void*
指针进行隐式转换为任何其他指针类型.
In C++
, you need the cast, since C++
does not allow implicit conversion of a void*
pointer to any other pointer type.
这篇关于c ++-malloc转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文