On C programming language, I have encountered several ways to allocate memory for a data structure:
typedef struct Element
struct Element *next;
int main(int argc, char *argv)
/* Method NO.1 */
Element *ptr1 = malloc(sizeof(*ptr1));
/* Method NO.2 */
Element *ptr2 = malloc(sizeof(Element));
/* Method NO.3 */
Element *ptr3 = (Element*) malloc (sizeof(Element));
The best way by, in my opinion, a country mile. Remember that
sizeof *ptr1 is compile-time evaluable so there's no chance of a run-time crash due to dereferencing an uninitialised pointer.
Not my favourite way - despite it arguably being the most readable - since you might change the type of
*ptr2 and forget to adjust
sizeof Element. And those kind of bugs are a nightmare to track down.
Is horrible: the cast is unnecessary in C and is even occasionally harmful. See Do I cast the result of malloc?.