c++ - malloc casting error

我怕爱的太早我们不能终老 提交于 2019-12-14 03:36:06

问题


Everyones suggesting not to cast while allocating a pointer here, do I cast result of malloc

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;
}

Compiler error is,

1 IntelliSense: a value of type "void *" cannot be used to initialize an entity of type "int *"


回答1:


The advice in the other question is strictly for C only.

In C++, you need the cast, since C++ does not allow implicit conversion of a void* pointer to any other pointer type.



来源:https://stackoverflow.com/questions/47193926/c-malloc-casting-error

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