Array question

Doug Gwyn gwyn at smoke.brl.mil
Sat Feb 16 05:52:09 AEST 1991


In article <7060009 at hpfcso.FC.HP.COM> pgt at hpfcso.FC.HP.COM (Paul G. Tobin) writes:
>It would seem that today's compilers probably somewhat close the speed
>gap between array and pointer addressing, but I'd contend that they
>*can* be freely interchanged.  It all depends on your personal style.
>Use whatever mode seems more suited to the task at hand.

No, it is important to understand that pointers and arrays are NOT
freely interchangeable, in order to avoid programming errors.  In
most (but not all) expression contexts, the name of an array is
converted by the compiler to a pointer to the first element of the
array, and that pointer is used in the subsequent evaluation.  An
important exception is when the array name is the operand of the
"sizeof" operator; in such a situation the result of evaluation the
"sizeof" unary expression is the number of bytes in the entire
array, not the number of bytes in a pointer to an element of the
array (the latter is typically always 4, in many implementations).

The exact rules are spelled out in the C standard, and in A.7.1 in
the second edition of K&R these rules are summarized.  In the first
edition these rules do not seem to have been explained, although
certainly some of the exceptions were enforced by existing compilers
used as a basis for the notion of what the C language definition was
at the time of preparation of the first edition of K&R.  The main
new feature added for ANSI C is that the & operation can be applied
in a more menaingful way to an array (name) than was true for many
older existing C implementations.



More information about the Comp.lang.c mailing list