SUMMARY OF confusion with char *a and char a[NUM]

Barry Margolin barmar at think.com
Thu Dec 6 10:06:17 AEST 1990


In article <7676 at umd5.umd.edu> jjk at astro.umd.edu (Jim Klavetter) writes:
[Given the declaration: char a[NUM]; ]
>I guess my followup question is more theoretical in nature:  is this a
>good thing?  Why shouldn't 
>	 strcpy(string, a); 
>also send an error message since the man page explicitely says that a
>(in this case) is char*.  Conceptutually I understand that a copy (in
>this case) is fundamentally different than an equivalence (as above
>with strchr()), and also that a is unambiguous in this case, but as so
>many are willing to point out:  pointers are not arrays!  (and vice
>versa).  Thus, the man page is asking for a pointer, but I am giving
>it an array, yet it works.

I think Chris slipped the answer to this in the middle of one of his
responses, but it probably deserves repeating as an explicit answer to this
question.

In most cases, objects are passed to functions by value; that is, if an
argument expression is an lvalue, the contents of the location(s) specified
by that lvalue are copied to wherever the callee expects to find it
(usually the stack or registers).  The designers of C felt that this would
not be appropriate for arrays; they are often very large, and this copying
would be expensive.  So, they decided that arrays would be passed by
reference, rather than making the above syntax an error.  This was
implemented by specifying that when arrays are used in a value context they
are automatically treated as &array[0].

Basically, this is just a convenience for the programmer.  They could have
required an explicit cast, but since this use is so common it would be
quite a bother.  Also, to be completely type-proper, the reverse conversion
(passing a pointer to a function expecting an array) would require the cast
to include the size of the array.

>I'm certainly not a c basher, it just seems as if this is an
>inconsistency.

It's no less consistent than the fact that you don't generally have to cast
when assigning from an int to a long; the compiler automatically widens it.



--
Barry Margolin, Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list