Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site ucbvax.ARPA Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxn!ihnp4!ucbvax!anton From: anton@ucbvax.ARPA (Jeff Anton) Newsgroups: net.lang.c Subject: Re: C array follies 1 Message-ID: <10299@ucbvax.ARPA> Date: Sat, 7-Sep-85 13:56:11 EDT Article-I.D.: ucbvax.10299 Posted: Sat Sep 7 13:56:11 1985 Date-Received: Mon, 9-Sep-85 00:58:21 EDT References: <171@rtp47.UUCP> Reply-To: anton@ucbvax.UUCP (Jeff Anton) Organization: University of California at Berkeley Lines: 54 In article <171@rtp47.UUCP> throopw@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 >!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@BERKELEY.EDU