Using sizeof() on a parameter array

Chris Torek torek at elf.ee.lbl.gov
Thu May 23 03:16:25 AEST 1991


>In article <12151 at jarthur.Claremont.EDU> jseidman at jarthur.Claremont.EDU
(Jim Seidman) asks why `sizeof param' is 2 rather than 80 in:

>>void test(char param[80]) {

on his particular machine.

In article <1991May19.135611.6332 at monu0.cc.monash.edu.au>
ins845b at monu4.cc.monash.edu.au (mr  k.l. lentin) writes:
>C passes all arrays as pointers and as a stringis an array, it is passed
>as a pointer.

More precisely, a pointer to the first element of the array.

There is one major Rule about arrays in C, from which many lesser rules
follow.  The Rule is this:

    In any value context, an object of type `array N of T' is converted
    to a value of type `pointer to T' by locating the first element of
    that array.

All function parameters are value contexts, and all array objects are
`objects of type ``array N of T'' '---here param is an object of type
`array 80 of char'---and this means that there are no array parameters.
When you place an array-80-of-char in a parameter position it is changed
to a `pointer to char', pointing to the first character of the array.

So, you write:

	I have this function called test.  It takes one parameter,
	which is an array of 80 `char's.  The function has no return
	value.

The compiler reads this and thinks[%], `Array?  There ain't no arrays
here.  You must've meant that you put an array-80-char in as an
argument, and that's been converted to a pointer to char, so I'll just
*pretend* that that's what you wrote.'  The compiler pretends so
thoroughly that it later thinks you gave it:

	void test(char *param) {

and thus `sizeof(param)' is equal to `sizeof(char *)' and `sizeof(*param)'
is equal to sizeof(char) (which is always 1).
-----
[%] Anthropomorphic analogies, always available, are abilitating, although
    also aromatic. :-)
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list