Hi, I don't understand why we typecast malloc.

For example, while creating a string/character array, we normally do,

line = (char*)malloc(200 * sizeof(char));

assume we have already declared char* line;

I was just reading the malloc man pages and it says that malloc allocates that much memory and returns a pointer to the start address from where it allocated memory. All that's cool, but why do we typecast it to char*. What is the default data type of the address it returns? Is it void or something, that's the only possible explanation I can think of really..

It used to be necessary, but that has been deprecated for a long time now. You should NOT cast the return from malloc (which is a void pointer), because it is automatically right for every data type.

There are cases where the data type is not a basic type in C, when a cast becomes necessary, but it is rarely the case.

It used to be necessary, but that has been deprecated for a long time now. You should NOT cast the return from malloc (which is a void pointer), because it is automatically right for every data type.

There are cases where the data type is not a basic type in C, when a cast becomes necessary, but it is rarely the case.

cool ! :)

This article has been dead for over six months. Start a new discussion instead.