Frequently Asked Array Questions

eric.a.olson junk1 at cbnews.att.com
Sat Mar 30 16:01:46 AEST 1991


>Section 2. Arrays and Pointers
>
>20.  So what is meant by the "equivalence of pointers and arrays" in C?
>
>A:   An identifier of type array-of-T which appears in an expression
>     decays into a pointer to its first element; the type of the
>     resultant pointer is pointer-to-T.

    Exactly what kind of expression?
    Not, for instance, one where an lvalue is expected... now:

    I have been writing in C since '82 and thought that I had it down.
    Read K&R and K&R 2 religiously.   Became the person that others
    came to with C questions.    Followed Chris et al here as well.
    Today, I ran across a situation where a peer had:
	func()
	    {
		char array[7];
	    
	    if (array == 0)
		something;
	    }
    His code wasn't working.   I looked thru the rest of the code
    and suggested that he wanted 'array[0] == 0' rather than 'array == 0',
    and I furthermore charged that the compiler had warned him about
    this, and that he had ignored it.

    Well, it just ain't so.   No compiler we have complains about it.
    They complain about a test for equality with any other constant
    but 0, but even then, only that it is an illegal pointer/integer 
    combination.   (I understand that difference).

    It seems to me that a comparison between something of type
    auto array and something of type constant ought to at least produce
    a warning.  It's not like we're supposing even that it might be
    an extern and that the linker bound it to 0.

    I posed this to john ampe here at BL and he finally came up with this
    argument:
	the following is clearly legal:
	    {
		char x[7];
		char *p;
	    for (p=x+3; p != x; --p)
		something;
	    }
    therefore, testing an auto array name for equality to a constant
    is legal as well, since if you reduce the types you have the same
    types in both cases.   

    After looking at this, and the above excerpt from the FAQ, I had to
    concede that such a test was valid.  However,  I still feel a little
    strange about it.

    Can anyone here give another reason why this test is legal, or expound
    upon john's example?   Feel free to reply directly to:
					eao at mvucl.att.com



More information about the Comp.lang.c mailing list