c++ - malloc casting error

2019-09-24 07:56发布

问题:

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.