Clarification needed on Pointers/Arrays

Karl Heuer karl at haddock.ima.isc.com
Thu Feb 23 09:29:32 AEST 1989


In article <889 at acf3.NYU.EDU> sabbagh at acf3.UUCP () writes:
>In article <1436 at etive.ed.ac.uk> sam at lfcs.ed.ac.uk (S. Manoharan) writes:
>>main() {
>>   static char *a[] = { ... };
>>   foo1(a);
>>}
>>
>>foo1(b) char *b; { ... }

Type mismatch: foo1() invoked with (char **) but declared with (char *)
Later comments suggest that you meant to invoke foo1(a[0]) instead.

>>foo2(b) char *b[]; {

Warning: C does not allow arrays as formal arguments; declaration will be
interpreted as `char **b'

>>   printf("Entries %d\n",sizeof(b)/sizeof(char *));

Warning: previous rewrite causes sizeof(b) to be misleading.

>>   for ( i = 0; i < 4; ++i ) printf("%d: %s\n",i,b[i]);
>>}

wlint: 1 error and 2 warnings produced.  Stop.


>Simply put, a pointer to blah should be considered a different type than blah.

Of course.  It *is* a different type.  Even if blah is a function type.

>Now, according to K & R, the notation
>	p1[j]
>is in ALL WAYS equivalent to
>	*(p1 + j)

Minor nit: they are equivalent in expressions, but not in declarations.

>(Incidentally, this implies that p1[j] == j[p1]) !!

A fact used primarily by the Obfuscated C Contestants.  I wish X3J11 had fixed
this.  (They could use the same justification that they did for fixing `+ ='.)

>So what are arrays?  They are POINTER CONSTANTS.

Urk.  While this is true in a sense, it's been my observation that people who
think of them that way are taking the wrong path to understanding.  It becomes
a pointer after the transformation (array-valued expressions decay into
pointer-valued expressions when used in an rvalue context), in which case its
value is constant throughout its lifetime.  This is independent of its lvalue
properties, but some people believe that this is the reason that the lvalue is
not modifiable.  This is not the case; it would be a relatively simple
extension to the language to allow array copy.  (It is hindered only by the
fact that X3J11 didn't fix the declaration botch noted in the first warning
message above (and in fact paved the way for reinterpreting it according to
the Darnell syntax rather than the more logical Brader-Heuer syntax), and by
the opinion that array copy with compile-time array sizes is not especially
useful.)

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list