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 don't cast the result of malloc , because doing so adds pointless clutter to your code. The most common reason why people cast the result of malloc is because they are unsure about how the C language works.
It is not required to typecast. The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL .
realloc() function need to be type casted because the address returned by the realloc() does not represent any data type. realloc() function may change the address of the previously allocated block, so it is recommended to store the new address in pointer or use some new pointer to store the reallocated address.
We can use the process of type casting to convert the character (char) data type to the int (integer) data type in C. When we are performing a conversion between these two, the resultant value would be an integer (int) data type. It is because the int data type is comparatively bigger than the char data type in C.
You compiled this C program using a C++ compiler. It is necessary to cast the result of malloc in C++, but not in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With