Re: Array and Pointer Tutorial



Chad said:

I can't really put me pinpoint the exact part, but I know I'm missing
some kind of underlying concept when I see the construction:

int *q = malloc(sizeof *q);

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.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.



Relevant Pages

  • Re: Array and Pointer Tutorial
    ... I can't really put me pinpoint the exact part, but I know I'm missing ... some kind of underlying concept when I see the construction: ...
    (comp.lang.c)
  • Re: function call in conditional operator?
    ... >> BTW what other seemingly strange standard C construction ... object type', the second expression shall have integral type" wouldn't ...
    (comp.lang.c)