T
Tim Rentsch
Alok Singhal said:int a[20] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int (*p)[5] = (int(*)[5])(a+6);
Think again. The purpose of the cast is not to silence the warning but
to coerce the value of the expression to a compatible type and eliminate
the condition that requires a diagnostic.
The code
unsigned char *ptr = (unsigned char*)(a+6);
will produce the exact same warning without the cast yet the
initialization is perfectly well defined as written.
Thanks. This is what I was looking for. I should have read the standard
more carefully as well. So 6.3.2.3p7 (N1336) applies here:
A pointer to an object or incomplete type may be converted to a
pointer to a different object or incomplete type. If the resulting
pointer is not correctly aligned for the pointed-to type, the behavior
is undefined. Otherwise, when converted back again, the result shall
compare equal to the original pointer.
There is no guarantee that int (*)[5] is correctly aligned for int *, and
even if it is, the standard makes no guarantees about dereferencing such
a pointer.
There is no guarantee that (a+6) is correctly aligned for int (*)[5],
but if it is then since it does point to an object that is suitably
composed to be one (or two) array(s) of (int[5]), and since both the
element types are (int), dereferencing it will work fine.