Necessity of use (float*) before malloc
This question already has an answer here:
Malloc returns a pointer to void.
(float*)
casts from a pointer to void to a pointer to float
In C this is not necessary, in C++ it is, so some people recommend that to make your code compatible with C++ compilers.
But you don't need to do that. (and some C fans are against it)
malloc
will give you a pointer to void
that you can't use for anything related to things you want to do with a float
. To be able to use the variable allocated at the returned memory location, you need to cast it to a float*
so you can dereference that pointer and use it as a float
.
But, as you've written your question, you should cast the return value of malloc
to float*
and then immediately dereference it before assigning it to x
, since you've not declared x
as a pointer to float
.
EDIT: As commenters pointed out, the explicit cast is only needed in C++, not in C.
链接地址: http://www.djcxy.com/p/28430.html