Thread: malloc function and typecast

  1. #1
    Registered User
    Join Date
    Mar 2006
    Location
    Honolulu, HI/United States
    Posts
    12

    malloc function and typecast

    Why would I want to typecast the malloc function? The reason I ask this is that I never have but have seen numerous tutorials with examples of them doing this including cprogrammin.com.

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    You don't typecast the malloc function. The reason you see it cast all the time is because back in the day, C didn't use void pointers and malloc was defined with a char pointer. So if you tried to assign the return of malloc to anything but a character, you'd get a problem, so you cast it. Since then, it's used a void pointer and is not required to be cast.
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Mar 2006
    Location
    Honolulu, HI/United States
    Posts
    12
    Thx Slymaelstrom as you have cleared this up for me. Didn't know the old function declaration was different.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to function won't
    By samGwilliam in forum C++ Programming
    Replies: 23
    Last Post: 09-03-2008, 05:37 AM
  2. how to convert return type of function at run time ?
    By vinod_mrd in forum C++ Programming
    Replies: 26
    Last Post: 01-26-2008, 11:49 AM
  3. function pointer and void*
    By Sargnagel in forum C Programming
    Replies: 8
    Last Post: 08-29-2003, 07:30 AM
  4. Data init inside of template class function
    By VirtualAce in forum C++ Programming
    Replies: 1
    Last Post: 04-24-2002, 03:11 PM