Any time you're allocating space for a pointer p to point to,
it can be a good idea to use the idiom
p = malloc(n * sizeof(*p));
rather than the more obvious
p = malloc(n * sizeof(int));
(where of course the type we need the size of isn't necessarily int,
but rather whatever type it is that p points to[footnote]
).
The reason is that the code is more self-contained,
more self-documenting,
and more robust:
a reader looking at
p = malloc(n * sizeof(*p));
can see immediately that the correct amount of space is being allocated,
without looking back at p's declaration to see what type it is.
If p's type ever changes,
the malloc call may not have to change.
The sizeof(p) form can also be seen
in the array4 and array5 examples.
back
about this FAQ list
about eskimo
search
feedback
copyright
Hosted by