sizeof() confusion

Paul John Falstad pfalstad at phoenix.Princeton.EDU
Mon Nov 5 17:32:11 AEST 1990


In article <9156 at latcs1.oz.au> jacob at latcs1.oz.au (Jacob L. Cybulski) writes:
>typedef unsigned char Pattern[8];
>
>void foo (Pattern x)
>{
>/* 0 */	printf("%d\n", sizeof(Pattern));			/* prints 8 */
>/* 1 */	printf("%d\n", sizeof(x));			/* prints 4 */
>/* 2 */	printf("%d\n", sizeof(*x));			/* prints 1 */
>/* 3 */	printf("%d\n", sizeof((Pattern) x);		/* illegal */
>/* 4 */	printf("%d\n", sizeof(*((Pattern *) x)));	/* prints 8 */

(I added some missing parens)

>The intuition says that sizeof(Pattern) = sizeof(x) regardless of the
>Pattern definition.

This is true, if x is of type Pattern.  It isn't in this case, although
it looks like it.

							Well, not in C, if Pattern is an array then it is
>implemented as a pointer so sizeof(x) is a pointer length (case 1), *x is an

Not quite.  Arrays used as function arguments are implemented as
pointers.  void foo (Pattern x) is equivalent to void foo (char *).

>address of the first array element so it's length is that of its elements
>(case 2), the cast of x into its type is illegal possibly because x is
>implicitly defined as a (Pattern *) (case 3), finally a convoluted casting

x is implicitly defined as a char *.  You can't cast something to an
array.

>Now is it the fault of my compiler (THINK C) to give me such a hard time,
>is it my bad C programming style, or is it the ANSI standard which has some
>gaping semantic holes?

The ANSI standard is giving you these results.  I don't consider them
gaping semantic holes.  As long as you remember that whenever you pass
an array as a function argument, a pointer is actually passed, the above
all makes sense.  To make it clear, you should probably declare foo as
void foo(char x[]) or void foo (char *x).  That style also emphasizes
the fact that the called function just gets a pointer to the first
element of the array, and therefore cannot possibly know the size of the
array, so sizeof will not work.

--
Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
"Your attention, please.  Would anyone who knows where the white courtesy
phone is located please pick up the white courtesy phone."



More information about the Comp.lang.c mailing list