Why must I cast the result from malloc?

The following code gives the error "error: invalid conversion from void* to char* [-fpermissive]"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
    char *t = malloc(20);
}

However, casting the result of malloc solves the problem. But I cannot understand why as this question says that casting the result of malloc is not needed.


You compiled this C program using a C++ compiler. It is necessary to cast the result of malloc in C++, but not in C.


Is it possible that you are compiling the code as c++? In c++ the cast would be required.


In your case,

malloc(20);

will assign memory as required and will return a pointer which can be assigned to any pointer, as explained in this document

As pointed out, you probably are using C++ compiler, because in C its actually considered a bad practice to cast result of malloc.

链接地址: http://www.djcxy.com/p/4868.html

上一篇: 你投了malloc的结果吗?

下一篇: 为什么我必须从malloc投出结果?