Re: Type casting with malloc()
holotko wrote: Let's say I want to dynamically allocate some memory to an object that I am creating using malloc(). Traditionally I do the following: ObjectType *objectpointer; /* Decl. of pointer to object */ objectpointer = (ObjectType *)malloc(sizeof(ObjectType)); My question. Do I really need to add the type cast (ObjectType *) before the call to malloc() ? In ANSI C, no. In KR C yes. Traditionally I have always been taught to include the cast. However, some references say that a cast was ONLY required in earlier versions of C prior to standard ANSI C. Nonetheless I always type cast as that is how I have done it for years and years. Do I really need the cast? ANSI C defines malloc() as returning a `void *', while KR C defines it as returning a `char *'. You can implicitly cast to or from void pointers, but casting between other pointer types requires a cast. More precisely, do I really need the cast using gcc? Not if you're using an ANSI libc (e.g. any of the ones which are used on Linux). -- Glynn Clements [EMAIL PROTECTED]
Re: Type casting with malloc()
On Thu, 1 Apr 1999, holotko wrote: # My question. Do I really need to add the type cast (ObjectType *) # before the call to malloc() ? no. but gcc will warn you, if you use -Wall, about it. Doesn't do any harm leaving it in and if you miss it out gcc will add it in itself. Technically you need it because malloc returns memory cast to void *, which your data structures aren't. Makes your code more readable if you include it though. -- +++ If at first you don't succeed, you must be a programmer +++ [EMAIL PROTECTED] http://www.users.globalnet.co.uk/~kermit