C array follies 1

Jeff Anton anton at ucbvax.ARPA
Sun Sep 8 03:56:11 AEST 1985


In article <171 at rtp47.UUCP> throopw at rtp47.UUCP (Wayne Throop) writes:
>Consider the following program:
>
>    void f(x)
>        int x[2][2][2];
>    {
>        printf( "%o %o %o\n", x, x[0], x[0][0] );
>        printf( "%d %d %d\n", sizeof(x), sizeof(x[0]), sizeof(x[0][0]) );
>    }
>    void main(){
>        int x[2][2][2];
>        printf( "%o %o %o\n", x, x[0], x[0][0] );
>        printf( "%d %d %d\n", sizeof(x), sizeof(x[0]), sizeof(x[0][0]) );
>        f(x);
>    }
>Clearly the printfs are "illegal", but assume you have a fairly vanilla
>machine.  Eight-bit bytes, four-byte ints.  Four-byte pointers.
>Two questions:
>  - What does this program print?
>    (Especially what is printed on the last output line?)
>  - Is this "correct"?  (Again, especially the last line.)
>
>I think that most systems will print "4 16 8" (or equivalent) as the
>last line.  While this is (probably) not a bug, I think it is at least a
>misfeature.  This same point was part of the "C bites" topic, which is
>what drew my attention to it.  The point is *should* C bite in this way,
>and if so, why?
>-- 
>Wayne Throop at Data General, RTP, NC
><the-known-world>!mcnc!rti-sel!rtp47!throopw

sizeof returns the size of the object.  Since arrays are passed as addresses
which are put into pointer vars, sizeof(x) in the called function should be
the sizeof the pointer.  Are you proposing that C should pass the dimentions
of the array also so a called function can know these things?  Or maybe
since the pointer was declared as 'int x[2][2][2];' you want sizeof x to
be 8 ints?  I prefer to keep C's ability to pass pointers to arrays or
subarrays.  A use of sizeof often has the address taken also so returning
the size of the pointer not the array it points to prevents a careless
programmer from stomping over memory.  As far as debugging goes, I
hate large memory updates that might run to far or not far enough.
They are probably the must tricky bugs around.  If you know the size of
an array because you know its dimensions, you might as well put a
#define XSIZE 2*2*2*sizeof(int)
in near your declaration.
	Perhaps it might be nice to pass array dimensions by arguments
to function calls.
-- 
C knows no bounds.
					Jeff Anton
					U.C.Berkeley
					Ingres Group
					ucbvax!anton
					anton at BERKELEY.EDU



More information about the Comp.lang.c mailing list