sizeof and multi-dimensional arrays

Bull Engineers bull at ccs.carleton.ca
Sun Jan 6 10:22:25 AEST 1991


]>>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.



More information about the Comp.lang.c mailing list