Path: utzoo!attcan!uunet!auspex!guy From: guy@auspex.auspex.com (Guy Harris) Newsgroups: comp.lang.c Subject: Re: Another silly question Message-ID: <1647@auspex.auspex.com> Date: 18 May 89 16:46:57 GMT References: <17812@cup.portal.com> <607@kl-cs.UUCP> Reply-To: guy@auspex.auspex.com (Guy Harris) Organization: Auspex Systems, Santa Clara Lines: 54 >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").