C pointers

Ray Butterworth rbutterworth at watmath.waterloo.edu
Wed Feb 15 03:54:25 AEST 1989


In article <11217 at ulysses.homer.nj.att.com>, cjc at ulysses.homer.nj.att.com (Chris Calabrese[mav]) writes:
> In article <11216 at ulysses.homer.nj.att.com>, I write
> > Um...isn't (*p_cmd_blk)[] an array of pointers, not a pointer to an array?
> > try *(p_cmd_blk[]).
> 
> These things always confuse me to no end.
> Advanced C Tips and Techniques (page 218) says (*foo)[] should be a pointer
> to an array.  I still think a pointer to a pointer is the best way.

They are only confusing if one tries to think about it.
The trick is don't think.

i.e.  read it exactly as it says it is, and in the occasional case
where the type you end up with really is array, and if array is not
meaningful in the context, then and only then change array to pointer
to element of array.

e.g. (*foo)[3] explicitly says foo is a pointer to an array of 3
elements, so, if you use sizeof(*foo), then you should get the size of
the array, since that is exactly what you asked for,
but if you use func(*foo), then since it is not possible to pass
arrays to functions you get a pointer to the first element of *foo.
Similarly if you have "x = *foo;", then *foo is an array, but since
you cannot assign arrays (i.e. have them on the right of an =,
i.e. have them as r-values), the compiler silently turns the
reference to the array to a pointer to its first element.

Another handy style guideline to follow is trying to avoid writing
empty [] declarations.  If the [] is empty, then you are talking
about an array of unknown size and in the event that you really do
want the array there is no way that the compiler will know how big
it is.  If you don't know how big an array is, then perhaps you
shouldn't be talking about arrays but about pointers.

In particular never declare a function parameter as an array.
e.g. use "char **argv;", not "char *argv[];".  Since the compiler
will silently convert the second parameter declaration into the
first for you, you might as well declare it that way in the first
place and avoid confusing yourself and others.



More information about the Comp.lang.c mailing list