allocating arrays

Wayne Throop throopw at dg_rtp.UUCP
Fri May 23 08:26:12 AEST 1986


> david at ukma.UUCP (David Herron)
>> throopw at dg_rtp.UUCP (Wayne Throop)

Oh yeah, about that example the pcc says "illegal lhs" about...
(Don't know how I let this slip by before.  Oh well, I can fix it now.)

>>        void f(){
>>            double (*a[15])[];
>>            char *malloc();
>>            a[0] = (double *)malloc((unsigned)sizeof(double)*75);
>>        }
>>lint (on our system at least) says
>>        warning: illegal pointer combination
>>            (4)
>
> Right.  the pcc says "illegal lhs" or something to that effect.  Which
> is correct... there's no space allocated to your a.

Wrongo.  The array "a" is an array of 15 pointers to arrays of double
(is anybody getting bored with this?), and thus has 15 pointer-sizes
allocated for it, on the stack in this case.  Take this program for
example:

        void main(){
            double (*a[15])[];
            printf( "elements in a = %d\n",
                sizeof(a) / sizeof( double (*)[] ) );
        }

Now, let's examine this program with a debugger.  Positioning to this
module, and asking it to describe "a", we get

        ARRAY [ 0..14 ] OF POINTER TO ARRAY [ 0..0 ] OF FLOAT BOUND 64

That is, this is an array of pointers to arrays of doubles, just as I've
been trying to *tell* you.  In particular, there are 15 pointers in this
array (that is, the bounds are 0 to 14).  But let's see how much space
the compiler has allocated for this array on the local stack frame.  We
position to main, and disassemble the first instruction (the allocation
of stack space), and find

         WSAVR   17

OK.  That's 15 (octal 17) 32-bit words of storage allocated to "a".
Finally, let's run the blasted thing, and see how many elements *IT*
thinks it allocated for "a":

    elements in a = 15

If the pcc says that the assignment is illegal, that's fine with me
since it (sort of) is.  But it had better be able to accept

        a[0] = (double (*)[])malloc((unsigned)sizeof(double)*75);

Now *this* assignment is perfectly legal, since a[0] is a pointer to
an array of double (that is, (double (*)[])).

Fairly conclusive, I'd say.  Are y'all convinced?

--
   "I've seen things you people wouldn't believe. Attack ships on fire
off the shoulder of Orion. I watched C-Beams glitter in the dark near
the Tanhauser Gate. All those moments will be lost in time, like tears
in rain. Time to die."
                         Roy Baty, N6MAA10816, Nexus6, Combat Model
--
   "I've seen blunders you people wouldn't believe. Pointers confused
with arrays as arguments. I watched C-hackers make stupid mistakes on
net.lang.c.  All of these moments will be lost in time, like a posting
on net.philosophy.  Time to logout."
                        Wayne Throop, throopw at dg_rtp, Comedy Model
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.unix mailing list