C language: pointer returned by malloc() and casting

Possible Duplicate:
Do I cast the result of malloc?
What is the Best Practice for malloc?

Im new with c language and i have a question as i was explained in class:

The type of the pointer returned by malloc() is void *, and therefore we need to cast it into the required type

which means i need to do:

char *str;
str = (char *) malloc(14);

but i dont understand, is it a must? lets say malloc returns that void pointer, why do i see many of examples around without doing the casting? an example:

float *arr = malloc (20 * sizeof (float));

Could anyone please explain :) ?


In C, this cast is not required. The conversion is indeed implicit.

C11 (n1570), § 6.3.2.3 Pointers

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Since it is unecessary, cast malloc return or not is another question (see here).

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

上一篇: malloc转换错误

下一篇: C语言:由malloc()返回的指针和转换