Newsgroups: comp.lang.c Path: utzoo!utgpu!cunews!bull From: bull@ccs.carleton.ca (Bull Engineers) Subject: Re: sizeof and multi-dimensional arrays Message-ID: <1991Jan5.232225.14909@ccs.carleton.ca> Organization: Carleton University, Ottawa, Canada References: <1991Jan5.050613.22303@Neon.Stanford.EDU> <4596@sactoh0.SAC.CA.US> Date: Sat, 5 Jan 91 23:22:25 GMT ]>>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). ] Sorry, sizeof(*x) makes perfect sense. Remember, the * operator means "evaluate what's at this address". This means, that for two-dimensional arrays, *x and x[0] are identical by definition. Try this with a three dimensional array z[2][3][4]. sizeof(z) = 24, sizeof(z[0]) = 12, and sizeof(*z) = 12 also. Why? Because *z dereferences the first (0th) dimension of z.