Say I have the following struct:
typedef struct elementT {
int value;
struct element *next;
} element;
What would be the difference between doing:
element *newElem;
newElem = malloc(sizeof(element))
And doing this:
element *newElem;
newElem = (element *) malloc(sizeof(element))
From my point of view, in the first case we are doing:
element *newElem; -> Create a pointer for an address that contians an element type.
newElem = malloc(sizeof(element)) -> Make that pointer to point to the result of the malloc.
Why do we need to do (element *), or why is it useful?
Thanks
It’s from old style C where
void *wasn’t really allowed so everything returnedchar *, this would cause the compiler to generate a warning saying that you were assigning incompatible pointer types and casting was simply a way to get rid of this warning. Newer compilers know what you are trying to do and make the cast unnecessary (except in certain situations such as the Linux kernel vmalloc function).