i got the following:
I am a bit confused with the malloc. Why do you have to do this, (frac *) , before it??Code:typedef struct { int n, d; } frac; int main(void) { frac *f1; f1 = (frac *) malloc(sizeof(frac));
i got the following:
I am a bit confused with the malloc. Why do you have to do this, (frac *) , before it??Code:typedef struct { int n, d; } frac; int main(void) { frac *f1; f1 = (frac *) malloc(sizeof(frac));
You don't. In fact, you shouldn't.
(If your compiler is telling you you should, that's because you're using a C++ compiler.)
Or perhaps you forgot to #include <stdlib.h>.(If your compiler is telling you you should, that's because you're using a C++ compiler.)
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
Someone once told me that it did not matter if you did, because there are always tools to spot the bugs in your code.
So to answer the question: In C, you do not have to do it. You can, but you do not have to.
Is it good practice to do it? Debatable. I am sure many would have their own opinions.
Explicitly casting the return of malloc() is like saying, "I don't trust the language." The whole point (in C, not C++) of void * is that it can be silently converted to any other pointer type -- and any pointer type can silently convert to void *. Using an explicit cast is like denying this aspect of the language, and IMHO indicates a misunderstanding of the point of void * in the first place.
Calling functions without prototypes is just wrong. Including stdlib.h isn't optional.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
I am just saying that IMHO, since void* can be anything (as you say, any pointer type can be implicitly converted to void*), so that does not necessarily mean that void* is the type you are assigning to. Maybe it is merely my C++ background.
That casting the return can mask the call without prototypes is just wrong and it is bad compiler, but I concede that that is not the aspect I am worried about.
Anyhow. I am just pointing out that, no, it is not wrong to cast the return, and no, it is not wrong to not do it either. In C, it is a taste thing.
200% agreed.Calling functions without prototypes is just wrong. Including stdlib.h isn't optional.
I never once said the word "optional" I said I appreciate his use of proper coding.