Given
struct node
{
int a;
struct node * next;
};
To malloc a new structure,
struct node *p = malloc(sizeof(*p));
It is convenient, because you can convert this:
struct node *p= malloc(sizeof(*p));
Into this:
#define MALLOC(ptr) (ptr) = malloc(sizeof(*(ptr) ))
struct node *p;
MALLOC(p);
Or, for an array:
#define MALLOC_ARR(ptr, arrsize) \
(ptr) = malloc(sizeof(*(ptr) ) * arrsize)
struct node *p;
MALLOC_ARR(p, 20);
And why is this safe? Because the user who uses these macros would be less likely to make mistakes which were outlined by AndreyT, just as in the case of DIM()
to get the size of a static array.
#define DIM(arr) ((sizeof(arr))/(sizeof(arr[0])))
This is also safer, because the user does not need to make the static array size consistent in several places. Set the array size in one place and then just use the DIM()
and you're done! The compiler takes care of it for you.