sizeof() confusion

Jacob L. Cybulski jacob at latcs1.oz.au
Mon Nov 5 14:46:23 AEST 1990


Being relatively new to C, I found a bit of a problem with a THINK C program
that goes more or less like this :-

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 */
}

The intuition says that sizeof(Pattern) = sizeof(x) regardless of the
Pattern definition. 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
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
and redirection gives you the right answer (case 4). Sure, it would simple
and "portable" to say sizeof(Pattern), but if you did use sizeof(x) then
your function becomes context dependent and you cannot rely on the
macro-expanded code anymore.

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?

Any answers?

Jacob L. Cybulski

Amdahl Australian Intelligent Tools Program
Department of Computer Science
La Trobe University
Bundoora, Vic 3083, Australia

Phone: +613 479 1270
Fax:   +613 470 4915
Telex: AA 33143
EMail: jacob at latcs1.oz.au



More information about the Comp.lang.c mailing list