Is a type required in malloc?

What is the use of typecast in malloc? If I do not write the type in malloc, then what will it return? (Why is casting required in malloc?)

+5
source share
5 answers

I assume you mean something like this:

int *iptr = (int*)malloc(/* something */);

And in C, you do not need (and should not) drop the return pointer from malloc. This is a void *and in C, it is implicitly converted to another type of pointer.

int *iptr = malloc(/* something */);

It is the preferred form.

This does not apply to C ++, which does not support the same void *implicit behavior.

+12
source

malloc(), C. :

  • , void * ( , ).
  • , ( ).
  • , , .

: , , , .

+5

, malloc a void *, void* , . , , .

+1

, :

  • , malloc() - , asap;
  • , char *, ptr ++ , , : 1 ( , 1 char).
0

All Articles