0

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 :) ?

Community
  • 1
  • 1
Popokoko
  • 6,413
  • 16
  • 47
  • 58
  • A void pointer can be converted to and from any (non-function) pointer **without a cast**. You don't need the cast. Remove it, since it is just cargo cult/ candy. – wildplasser Jan 19 '13 at 13:30
  • http://c-faq.com/malloc/mallocnocast.html – P.P Jan 19 '13 at 13:31
  • Basically, you don't cast it because it's dangerous. –  Jan 19 '13 at 13:33
  • [**Do I cast the result of malloc?**](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc?answertab=votes#tab-top) – Grijesh Chauhan Jan 19 '13 at 13:35

1 Answers1

1

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).

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93