#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    101
    Rep Power
    0

    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:

    http://www.cprogrammingexpert.com/C/Tutorial/dynamic_memmory_allocation/malloc.aspx

    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
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    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

    Jim
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1803
    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.

IMN logo majestic logo threadwatch logo seochat tools logo