sizeof(array)
D. Chadwick Gibbons
chad at csd4.csd.uwm.edu
Tue Aug 22 13:23:45 AEST 1989
In article <1989Aug22.024808.17913 at ctr.columbia.edu> Seth Robertson writes:
|I have a problem in that when I pass an array, it loses track of its size.
[example program deleted]
As you conjectured, the parameter passing mechanism of C is indeed
only passing an address to your array. You must remember that in C, arrays
are almost nonexistant. Compilers convert array references (or at least, they
are _supposed_ to) to a pointer/offset expression in the form of: (*(a + i))
which would equal a[i] in the original program. Arrays declarations in C
allow for little more than an easier way to initialize the size and contents
of a block of memory. This also explains why a is a rvalue and expressions
such as a++ are illegal. This can cause confusion to many new C programmers,
especially since there is a large following who declare the second argument to
main (argv) as char *argv[]; when really this isn't the case - it's done to
point out that argv is a "constant" size.
|In case you are wondering, yes, there are good reasons for making
|`printit' a subroutine, for passing code as a parameter instead of
|explicitly naming testcode, and for making testcode a global
|automatically initialized variable (variable only at compile time,
|obviously) sized array.
I might argue at your reasons for doing so, but I can see what you are
trying to accomplish. The problem of computing an array size can really only
be dealt with in two ways - there are probably more, but I can't recall them
at this time. One is to abuse the preprocessor and declare a constant
expression to the sizeof a given object. As an example:
#define ASIZE sizeof(testcode)
This has the disadvantage (or advantage, depending on how you look at it) of
being a compile time construction. The alternate way of computing an array's
size is to flag the end of an array with an nonused data combination - in a
string array, a zero length string comes in handy. This requires a loop to
determine the array size - yuck. The other problem of this is that it is more
than likely implementation dependent - an old version of the M-word (I can't
bring myself to say it) compiler used to place padding in arrays in order to
satisfy word alignment. Terrible.
There are other ways, of course: one that just came to my mind is
negative subscript to store the size, but this is clumsy and often more
trouble than it's worth. Reexam your code structure.
--
D. Chadwick Gibbons (chad at csd4.csd.uwm.edu)
More information about the Comp.lang.c
mailing list