sizeof and multi-dimensional arrays
Jay A. Konigsberg
jak at sactoh0.SAC.CA.US
Sun Jan 6 05:03:55 AEST 1991
In article <fred.663069060 at prisma> fred at prisma.cv.ruu.nl (Fred Appelman) writes:
>In <1991Jan5.050613.22303 at Neon.Stanford.EDU> dkeisen at Gang-of-Four.Stanford.EDU (Dave Eisen) writes:
>>Is the following a compiler bug or am I just confused?
>>
>>char x[2][3];
>> sizeof (*x) gives 6
>> sizeof (x[0]) gives 3.
>>What's the scoop?
>
>You are just confused.
>'x' is a two dimensional array of 2*3 elments of type char. Makes a total of
>6. 'x[0]' and 'x[1]' are arrays with a length of 3 elements. So both arrays
>have a size of 3.
>
Something is wrong here. I ran the program with the addition of sizeof(x)
and got the following:
sizeof(x[0])=3
sizeof(*x)=3
sizeof(x)=6
Also I bumped the array to "char x[5][6]" and got:
sizeof(x[0])=6
sizeof(*x)=6
sizeof(x)=30
This seems to be one of the finer differences between pointers and arrays.
sizeof(x) makes sense as it is returning the total size declared for
the array.
sizeof(x[0]) makes sense as it returns the total size of that dimmension
of the array.
sizeof(*x) DOES NOT make sense. The size of a pointer on this machine
is 4 bytes. (Note: adding "char *y; sizeof(y) does return 4).
--
-------------------------------------------------------------
Jay @ SAC-UNIX, Sacramento, Ca. UUCP=...pacbell!sactoh0!jak
If something is worth doing, it's worth doing correctly.
More information about the Comp.lang.c
mailing list