Another silly question

Guy Harris guy at auspex.auspex.com
Fri May 19 02:46:57 AEST 1989


>C does not really support arrays, and the square bracket operator ([]) is
>just syntactic sugar to make you think that it does! This works quite well
>until you see things like "hello"[2] == 2["hello"] which only look odd if
>you continue to think of them as arrays and not pointers.

If one says "C does not really support arrays", one should be careful to
indicate what one means; arrays really *are* arrays, not pointers.  E.g.,
on most C implementations,

	int	a[33];

causes a block of "33*sizeof (int)" bytes to be allocated; if it has
static storage duration (i.e., either external or static), a symbol "a"
or "_a" or whatever will probably be defined, and will refer to the
first location in that block - *not* to a block of size "sizeof (int *)"
that contains a pointer to the block of size "33*sizeof (int)".

However, array-valued expressions are, in most (but *not* all!)
contexts, converted to pointer-valued expressions; this is why "[]" is
sort of syntactic sugar.  "a[i]" gets turned into "*(a + i)"; the reason
this would work for the array "a" defined above is that in the context
of the expression "*(a + i)", the array-valued expression "a" gets
converted to a pointer-valued expression that points to the first
element of "a"; adding "i" to the value of that expression yields a
pointer that points to the "i"th element of "a", and dereferencing that
pointer yields the value of the "i"th element of "a".

The distinction between "arrays are pointers" and "array-valued
expressions get converted to pointer-valued expressions" is important;
the question "why doesn't this program work:

	foo.c:

	...

	int a[33];

	...

	bar.c:

	...

	extern int *a;

	...

" surfaces periodically in this group.  If arrays and pointers really
were the same thing, that program might well work; the reason it doesn't
work is that arrays and pointers *aren't* the same thing.  Similarly,
for the array "a" described above, "sizeof a" is "33*sizeof (int)",
not "sizeof (int *)" (although some compiler writers may have been
confused as well, and made their compilers give "sizeof (int *)" for
"sizeof a").



More information about the Comp.lang.c mailing list