C Coding Question

Wayne Throop throopw at dg_rtp.UUCP
Thu Aug 21 05:36:12 AEST 1986


> chris at umcp-cs.UUCP (Chris Torek)
>> gary at darth.UUCP (Gary Wisniewski)

>>> [ Original poster asks (among other things):
>>>     char *a[] = {"foo","bar"}; works...
>>>     will char **p = {"foo","bar"}; ?        ]
>>As far as your question about "char *help[]" and "char **help": the two
>>forms are IDENTICAL to virtually every C compiler (that's worth its
>>salt).  Arrays in C are merely special cases of pointers.  In other
>>words, both forms are correct.
>
> 	NO!
>
> Ai!  This has been asserted far too often.  Arrays and pointers are
> not at all the same thing in C!

Naturally, Chris is correct here, and points out that a reasonably
careful reading of K&R reveals the truth of the matter.  However, I'd
like to expand on the assertion that "virtually every C compiler [treats
char *x[] and char **x identically]".  In fact, I doubt that there are
very many such compilers.  I even think it is likely that the compiler
Gary uses does *NOT* treat these cases identically.  Which brings me to
the point.

TEST YOUR ASSERTIONS ABOUT THE C COMPILER BEFORE POSTING!

Let's see what we get when we try to compile this:

    char *a[] = {"foo","bar"};
    char **p  = {"foo","bar"};

Lint says

        (2)   **** cannot recover from this error ****

Not very informative, but should give you the idea that the declaration
of p is wrong, and the declaration of a is OK.  A local typechecker says

        2   too many values in initialization
        2   wrong type initializer

Ah.  A little more informative.  We are trying to initialize a single
pointer value with multiple pointers.  And they have type mismatch
problems (we are trying to initialize a (char **) with a (char *)).
Last, let's see what the compiler says.

        char **p  = {"foo","bar"};
                           ^
        You supplied p more initial values than there were variables
        or fields to initialize.  The compiler ignored the excess
        elements.

The compiler didn't diagnose the type mismatch problems because
typechecking isn't part of its job.

The point?   In this specific case, every C-understanding tool I
applied to the example Gary said would work for "every C compiler worth
its salt" found problems with it.  So, since they are easy to check,
CHECK THESE CLAIMS BEFORE YOU POST.

It helps to carefully read the standards.  But every assertion posted
about implementations of these standards ought to be backed up with an
example that has actually been fed to the compiler/tool/whatnot in
question.

--
You can't tell how deep a puddle is until you step in it.
                                --- Miller's Law
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list