C question

In a program I am working on, I put this on accident:

 
  float *coefficients = malloc(number_coefficients*sizeof(float));

instead of this:
 
  float *coefficients = (float *) malloc(number_coefficients*sizeof(float));

The program seems to work fine. Was I lucky that it worked, or is there some kind of implicit casting going on that makes the first version acceptable?
Thanks,
https://itrate.co/software-development/c/
Last edited on
(C++ is strongly typed so the first version wouldn't compile on a C++ compiler - just a by the way since we're in a C++ forum).

But C allows implicit casting from void* to any other data pointer. So both are perfectly fine, most people prefer the first version but it's your choice, both are correct.
> or is there some kind of implicit casting going on that makes the first version acceptable?
Yes, C permits the T* -> void* -> T* round-trip cast.
So there is no issue with assigning the void* result of malloc to your pointer variable.

Putting the cast in is actually a bad idea.
If you fail to include stdlib.h, then C will make an implicit declaration of 'int malloc();'.
But malloc doesn't return int, but a cast such as (float*) will hide that fact from you.
On machines where pointers and ints are different sizes, or returned in different machine registers, the code is broken.

It's better to leave off the cast, and trap potential failures to include stdlib.h.

Modern compilers can be made to warn about missing prototypes, but that's not universal.
Topic archived. No new replies allowed.