In article <17************ *************** *******@c19g200 0prf.googlegrou ps.com>
lovecreatesbea. ..@gmail.com <lo************ ***@gmail.comwr ote:
>Is it always legal to cast expressions of type of multi-dimension
array to type of pointer?
Including:
T[] to T* ,
T[][] to T* ,
T[][][] to T* ,
and so on...
It is certainly syntactically valid. It is a somewhat dodgy thing
to do, though.
Given an actual array object, even if it is an array whose elements
are in turn arrays, you can always compute the "value" of the
(outermost, in this case) array. That is:
T arr[M][N];
arr;
computes the address of the first element of arr, i.e., &arr[0].
In this case, this value has type "T (*)[N]", i.e., "pointer to
array N of T". (If "arr;" is the entire statement, this computes
the value, then discards it.)
If we have an array of arrays of arrays:
T arr2[Z][M][N];
then &arr2[0] has type "pointer to array M of array N of T", or
"T (*)[M][N]".
It is even (I claim) "semantical ly valid", at least in a dodgy
fashion, since (I claim) the address of the first element of the
array-of-arrays is always "alignment compatible" with the address
of the first element of the "innermost" array. In particular, see
<http://web.torek.net/torek/c/pa.html>, and consider that the
alignment requirements of each circle (or ellipse) are "the same",
as they are solely determined by the "innermost" element type
(the type named "T" in the original poster's question).
However, the folks who interpret the various C Standards (C89 and
C99) tell us that using this "innermost element" pointer to access
the entire array contents is not guaranteed to work. I think C
would be a better language if it *were* guaranteed to work, and
in practice it seems to work on all existing implementations ,
but it may be wise to avoid depending on it, "just in case".
Even if it does always work, the "dodginess" is emphasized by the
need for careful "programmer-level work" to understand, maintain,
and correctly manage all the "stride" information (as it is called
in compiler circles) needed to access each array element. (Again,
see the web page above.) C99's Variable Length Arrays provide a
convenient "compiler-managed" method of working with the necessary
stride information, so that the programmer does not have to do all
the grunt work. If C made the guarantees that I wish it did, you
could do this (manually) in C89, instead of relying on the C99
compiler's VLAs, but it is probably better to use the C99 feature.
(Of course, this assumes your C compiler supports it.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out)
http://web.torek.net/torek/index.html