Re: Array and Pointer Tutorial



"Rod Pemberton" <do_not_have@xxxxxxxxxxx> wrote:

"Richard Heathfield" <invalid@xxxxxxxxxxxxxxx> wrote in message
The canonical way to allocate space for n objects of type T is:

T *p = malloc(n * sizeof *p);

or, if p is already declared, simply this:

p = malloc(n * sizeof *p);

The reason this is the canonical way is that it doesn't rely on the type of
p, except that it must be an object type, not an incomplete type or
function type. If the type of p changes during maintenance, you don't have
to hunt down this line and hack it about. It will automagically work
correctly with the new type.

You should point out the negatives too. If p is already declared, and their
is no comment telling him what file p is declared in. He'll spend forever
trying to answer this question: "What the HELL is p?"

If he is a wise, old, experienced maintenance programmer, he'll ask the
same question of

p = malloc(n * sizeof (some_type));

because his experience tells him that somewhere along the line someone
has changed the definition of p to a type. With any luck, to a type just
smaller than *p, so that this still works, even though it is
semantically incorrect.

Richard
.