2

In the program of any pointer variable we often use :

float *x;
x=(float*)malloc(a*sizeof(long int));

I want to know why we use (float*) in front of malloc?

Marco Leogrande
  • 8,050
  • 4
  • 30
  • 48
user2100721
  • 3,557
  • 2
  • 20
  • 29
  • 1
    See [Should I explicitly cast malloc()'s return value?](http://stackoverflow.com/q/953112/1168156) – LihO Feb 22 '13 at 20:03
  • 1
    You use it because you haven't read [this article](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). –  Feb 22 '13 at 20:03
  • 7
    Why do you use `sizeof(long int)` for allocating an array of `float` ?? – Martin R Feb 22 '13 at 20:06

2 Answers2

1

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)

speeder
  • 6,197
  • 5
  • 34
  • 51
-2

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.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122