March 25th, 2013, 11:54 AM
Why cast with malloc()?
This is the following statement:
double * p = (double *) malloc (sizeof (double));
Why do you need to cast to be able to not get an error? (for me at least)
website I got this info from:
Can someone explain why it says "(double *)"? Is it because malloc() is void and it has to cast a double since the variable is assigned as a double? That's what I think, but I'm not 100% sure. Please clarify for me. thanks
March 25th, 2013, 12:11 PM
If you are using a C++ compiler then the cast is required.
If you are using a C compiler the cast is not required, nor is it recommended. Just be sure to include the stdlib.h include file to properly use this function.
Also that tutorial doesn't look to be very well written you may want to find a different one. Here is more information about casting malloc in C. http://c-faq.com/malloc/mallocnocast.html
March 25th, 2013, 01:03 PM
You get an error if you are using C++ compilation. If that is the case you would do better to use new rather than malloc().
Make sure your sources use the .c extension to force C compilation. Note that in GCC the extension .C (capital-C) is a C++ extension, not C.