C quiz questions/answers?

Rob Wehrli plug-devel@lists.PLUG.phoenix.az.us
Thu Nov 8 07:45:02 2001


On Monday, November 05, 2001 8:31 PM, Michael Wittman 
[SMTP:wittman@acm.org] wrote:
> On Mon, Nov 05, 2001 at 03:17:00PM -0700, Rob Wehrli wrote:
> > I've been writing an C "test" and thought that I'd ask the list for any
> > good traps/questions they might have...but not without at least 
offering
> > one.
>
> Part of this one bit me not too long ago...  Anyone want to guess the
> output?
>
>
> #include <stdio.h>
>
> void foo( char a[80] )
> {
>    char b[80] = "Hello world!";
>    char *c = "bar";
>
>    printf("sizeof(a) = %d\n",sizeof(a));
>    printf("sizeof(b) = %d\n",sizeof(b));
>    printf("sizeof(c) = %d\n",sizeof(c));
> }
>
> int main( int argc, char *argv[] )
> {
>    foo("012345678901234567890123456789012345678");
>
>    exit(0);
> }
>
>
> -Mike

The sizeof( a ) would be the size of a char pointer, typically 4 bytes, 2 
bytes on a DOS machine.  The sizeof( b ) would be the size of the declared 
array, which is 80 * sizeof( char ) which is 80 * 1 byte or just 80.  The 
size of the char pointer "c" would be the same as "a" since pointer sizes 
are constant on a per machine basis, which would mean that it would be 4 
bytes under Linux or NT and 2 bytes under DOS.

Take Care.

Rob!