Tejas Kokje said:
(e-mail address removed) wrote: [...]
what is the trade off between the following two allocations
1) p = malloc( sizeof(sn) );
2) p = malloc( sizeof(*p) );
I don't think there is any tradeoff as compiler already knows
pointer type of p and that *p is of type sn. So sizeof operator can
use sn or *p.
There's no tradeoff as far as the compiler is concerned, but code is
written for human readers, not just for the compiler.
However, I would prefer first syntax as it just tell me exactly what
data type is used in sizeof. In second case, I will have to tagjump
to know type of p.
It doesn't *tell* you what the data type is; it *assumes* a certain
data type. Suppose p is declared a a pointer to sn, but suppose there's
another type called "sm", and you accidentally type:
p = malloc( sizeof(sm) );
The compiler won't detect the error.
The advantage of the second form, which I'd write as:
p = malloc(sizeof *p);
is that you don't have to know the type to know that it's correct;
it's automatically correct.
Similarly, if you write an assignment
p = q;
the assignment itself doesn't tell you what type is being assigned.
If you need to know the type, you can search for the declarations of p
and q. That doesn't mean you should write:
p = (sn*)q;
to make the type explicit.