Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!munnari.oz.au!mel.dit.csiro.au!latcs1!jacob From: jacob@latcs1.oz.au (Jacob L. Cybulski) Newsgroups: comp.lang.c Subject: sizeof() confusion Message-ID: <9156@latcs1.oz.au> Date: 5 Nov 90 03:46:23 GMT Organization: Comp Sci, La Trobe Uni, Australia Lines: 42 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@latcs1.oz.au