Path: utzoo!attcan!uunet!cs.utexas.edu!tut.cis.ohio-state.edu!ucbvax!bloom-beacon!adam.pika.mit.edu!scs From: scs@adam.pika.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: sizeof(array) Message-ID: <13716@bloom-beacon.MIT.EDU> Date: 22 Aug 89 06:12:17 GMT References: <1989Aug22.024808.17913@ctr.columbia.edu> Sender: daemon@bloom-beacon.MIT.EDU Reply-To: scs@adam.pika.mit.edu (Steve Summit) Lines: 53 In article <1989Aug22.024808.17913@ctr.columbia.edu> seth@ctr.columbia.edu (Seth Robertson) writes: >I have a problem in that when I pass an array, it loses track of its size. [...passes array to subroutine, then tries to compute sizeof(array).] >I guess I understand what it is does (only passing the address, not any >additional information), but how do I get it to do what I want? Just call sizeof before the call, passing the size to the subroutine: printit(testcode, sizeof(testcode) / sizeof(testcode[0])); ... printit(code, nents) unsigned long code[]; int nents; This may seem slightly clumsy, having to compute sizeof() at the point of each call (you had wanted to centralize the sizeof processing in the printit subroutine, and centralization of common functionality is usually a good idea). However, the resultant subroutine is somewhat more general. For one thing, I find it's often convenient to define large data structures in separate source files, referenced at point of use with an extern declaration. In this case, I end up with something like extern unsigned long testcode[]; in the file making use of the testcode array, and I couldn't compute sizeof(testcode) (even if I wanted to) for a different but equally compelling reason. Therefore, I usually define another global int codesize = sizeof(testcode) / sizeof(testcode[0]); in the same file in which testcode is defined. The call is then extern unsigned long testcode[]; extern int codesize; printit(testcode, codesize); Passing in an explicit size to printit() also makes it useful for printing selected subparts of the array, and for handling the day when the array size becomes dynamic: unsigned long *testcode = NULL; int codesize = 0; ... codesize = 23; testcode = (unsigned long *)malloc(codesize * sizeof(unsigned long)); ... printit(testcode, codesize); Steve Summit scs@adam.pika.mit.edu