Tuesday, 21 March 2017

c - Why must I cast the result from malloc?



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



#include

#include
#include

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.


Answer




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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...